Page Jumping To Top When Clicking Link Containing Click Event

July 4th, 2013 - Posted by Steve Marks to Javascript / jQuery, Web Development.

There are number of reasons why you might want a link to not actually redirect the user to another page, but instead perform a specific JavaScript action. This might include such things as switching tabs, cycling through a carousel, or simply toggling a div.

To achieve this you might do something like so:

<a href="#" onclick="$('#my_div').toggle();">Toggle</a>

Or, if you have an event listener on the link it might look like this:

<a href="#">Toggle</a>
$(document).ready(function() {
    
    $('a').click(function() {
    
       $('#my_div').toggle();
    
    });
    
});

Both of the above will simply toggle a div with id ‘#my_div‘ when the link is clicked using jQuery.

What you’ll find however with these bits of code is, when the link is clicked, the div will be toggled but the page will jump straight to the top (if the page has a scrollbar). This is confusing and means the user loses their place on the page.

The Solution

The fix is a simple one and can be achieved by simply returning a value of ‘false’ once the actions have been carried out.

Let’s take the examples above and amend them to stop the page returning to the top:

<a href="#" onclick="$('#my_div').toggle(); return false;">Toggle</a>

Or:

<a href="#">Toggle</a>
$(document).ready(function() {
    
    $('a').click(function() {
    
        $('#my_div').toggle();
    	
        return false;
         
    });
    
});

In both of the above I have added ‘return false;‘ at the end. Note that this must be added right at the end, else everything else after it will be ignored.

This entry was posted on Thursday, July 4th, 2013 at 8:13 am by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first