Switching layouts page jumping (improvement to script)
I'm using this script to switch layouts in a page:
$("span.switcher").click(function () {
$("span.switcher").toggleClass("swap"); /*!*/
$("ol.search-results").fadeOut("fast", function() {
$(this).fadeIn("fast").toggleClass("grid");
});
The script works fine, the problem I have is that if the switch view is down the page, the layout chan开发者_运维技巧ges and then the page jumps back up.
If I add 'return false' right where you see the /* ! */ in the second line the script doesn't work.
Also, as you can see, I'm using < span > instead of < a > since I was told that using other element other than < a > would stop the page from jumping.
Any idea how to fix the jumping of the page?
Thanks.
As this blog post mentions, the page is scrolled up because
fadeOut sets the css property display to none.
The solution, also given in the blog, would be to use fadeTo()
instead of fadeOut()
and fadeIn()
, like this:
$("span.switcher").click(
function () {
$("span.switcher").toggleClass("swap");
$("ol.search-results").fadeTo("fast", 0,
function () {
$(this).fadeTo("fast", 1).toggleClass("grid");
}
);
}
);
Regarding using an
a
element instead of span
, you can do several things to prevent the default behaviour of the link (which would be to jump to the top of the page if its href
attribute was "#"
). How to do this and the effects of it is discussed in this SO question.You need to reference the event in the function call and stopPropagation on it:
$("span.switcher").click(function (event) {
event.stopPropagation();
$("span.switcher").toggleClass("swap"); /*!*/
$("ol.search-results").fadeOut("fast", function() {
$(this).fadeIn("fast").toggleClass("grid");
});
});
This stops the click from being notified to anything other than this binding.
精彩评论