Search code examples
javascriptjqueryanchorjquery-events

Why does clicking a link go to the top of the page?


This may sound a weird question, I have a page which has a link:

<a href="#" class="emails" > Email to Friends </a> 

Now I have an event attach to the anchor tag so that on click the given div toggle it state.

The Javascript Code look like this:

$(document).ready(function() {
    $(".emails").bind("click",function() {
       $("div#container").toggle
   })
})

Now the above code and all of it works fine, but here the big deal, when I click the given link the my focus of the page move to top of the page, and I have to scroll all the way down to see the change.

Can anyone help me on this?


Solution

  • It does this because the href="#" is an empty anchor. Anchors are used for linking to specific spots within a page. An empty anchor results in the page going back to the top.

    To fix this in your javascript, you need to prevent the click event from propagating or "bubbling" up the DOM. You can do this by returning false from your click event.

    $(document).ready(function() {
        $(".emails").bind("click",function() {
           $("div#container").toggle();
           return false; // prevent propagation
       })
    });
    

    You can also make the event available in the bind's click handler function by using an argument, usually named e. Having access to the event allows you to call methods on it such as .preventDefault().

    $(document).ready(function() {
        $(".emails").bind("click", function(event) {
           $("div#container").toggle();
           event.preventDefault(); // this can also go at the start of the method if you prefer
       })
    });