How To Prevent A Page From Jumping To Top When Showing Or Hiding Elements Using Jquery Fade Option
Solution 1:
Your second .back
onclick is never firing.
It doesn't work either time (as an a
or span
) - when it's an a
, the default click will fire which will take you to the top.
This is because when you call $('.back').on('click'..)
there isn't a .back
element to wire up to as you've not yet added that class to your back button.
You need to use event delegation: https://stackoverflow.com/a/1688293/2181514
Change your event wire up to:
$("document").on("click", ".back", function....
which will then pick up dynamically changed classes
Solution 2:
I doubt if your click
event on .back
is registered at all since when event is bound, .back
does not exist. Hence its as good as a click on link which has no href
.
You need to delegate click on .back
to the document
. This delegation is needed because you are adding the back
class dynamically.
$(document).on('click','.back', function(e){
e.preventDefault();
$('.items').fadeOut(300);
$('.category').html(response).delay(400).fadeIn(300);
$('#nav').html('CATEGORIES').removeClass('back');
});
Solution 3:
What you should do in html5, is use an anchor tag without the href
attribute.
In CSS you can use cursor: pointer
to compensate for that.
Then in JavaScript there's suddenly no need anymore for event.preventdefault
Solution 4:
A hacky solution is to set href="#/"
on an anchor tag, which would work. However, using anchor tags where they are not needed (if you use <a>
there should exist some clickable link) is not good practice for SEO.
Also, you could use e.preventDefault()
, but use it on all functions, not only on back click.
However, the better practice is to use <input type="button" />
, you eliminate those jumping problems and do better SEO.
Post a Comment for "How To Prevent A Page From Jumping To Top When Showing Or Hiding Elements Using Jquery Fade Option"