Search code examples
javascriptjqueryhtmlcssfixed

Prevent navigation to the top of the page after click on fixed top menu


I've been working on a new project recently and used the fixed top menu. In the top navigation menu I have and unnumbered inline list. I've got an element which is clickable and after click() it shows the vertical options that are inside the div.

I'm not sure if it's just the css mistake I did or I need to add something to make this work, but every time I click on this <li> element it navigates me to the top of the page and then shows the content of the div.

It's working at least, but I want the users to be satisfied with the functions on website, so I don't want the click() function to navigate me to the top of the page, but just to show fixed <div> from navbar that is aligned to my fixed navbar. Thanks for help.

**EDIT:**I forgot to say that after the <div> show() function I can easily move with that showed div on the site and it's fixed where it should be, but once again when I click on it to collapse it, the click() function navigates me to the top.

Here's the code:

HTML:

<li class="navbar_item navbar_item_left navbar_item_actions" onclick=">
                <a class="navbar_item_link navbar_item_link_for_actions refresher" href="#">Click me!</a>
                <div class="actions-dropdown">
                    <a href="#">First link</a>
                    <a href="#">Second link</a>
                    <a href="#">Third link</a>
                </div>
</li>

CSS:

.actions-dropdown {display: none; position: fixed; background-color: rgba(154, 210, 78, 1); width: 250px;}
.actions-dropdown a {color: rgb(250, 250, 250); padding: 8px; font-size: 15px; text-decoration: none; display: block; text-align: left; float: left; width: 234px;}

JS:

$(document).ready(function(){
   $(".navbar_item_actions").click(function(){
        var display = $(".actions-dropdown").css('display');
        if(display == 'none'){
            $(".actions-dropdown").show(400);
        } else {
            $(".actions-dropdown").hide(400);
        }
   });
});

Solution

  • Cancel the click so the default action (following the link) will not execute.

    $(".navbar_item_actions").click(function(e){
        e.preventDefault();
        /* rest of code */
    });