Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery make my page jump back to the top after click?

I have a general question about jQuery.

I have created few jQuery buttons but the problem that I have is when you scroll half way down the page and you press the button, the page jumps back to top, instead of staying in the middle where the button is??

How can you stop this from happening, as it's frustrating for the user??

Is there any particular reason why it's happening?

jsFiddle Example:

$(".comment-here").click(function() {
   $(".comment-form").slideToggle('slow');
});

$(".main-btn.orange").click(function(){
   $(".comment-form").slideUp('slow');
});
like image 619
user2965875 Avatar asked Nov 27 '13 16:11

user2965875


1 Answers

You're not preventing the default event. Since you're clicking on an anchor tag, the default event for # is just to jump up to the top of the document.

To prevent this from occurring:

Pass the event into the function, and use preventDefault();

$(".comment-here").click(function(e){
    e.preventDefault();
    $(".comment-form").slideToggle('slow');
})

$(".main-btn.orange").click(function(e){
    e.preventDefault();
    $(".comment-form").slideUp('slow');
})

You could also use return false; instead, which goes a bit further than just preventing the default event, it will stop events bubbling up to parent elements.

like image 183
Nick R Avatar answered Nov 14 '22 21:11

Nick R