Undesired page scroll when changing content of fixed element
So I've made a menu sort of thing, affixed to the bottom of the screen via CSS fixed position, and it works fine. Only problem is that when the page is scrolled down somewhat, and then the menu activated (slide up animated with jQuery), the page jumps to the top again. It's pretty irritating. Here's some pertinent code:
//handle click on stats tab
$('a.stats').click(function(e) {
if ($('#menuWrapper').hasClass("stats")) {
$('#menuWrapper').removeClass("stats")
.removeClass("open")
.animate({ bottom: '-100px'}, 300);
} else if (!$('#menuWrapper').hasClass("open")) {
$('#sponsors').hid开发者_如何学编程e();
$('#feedback').hide();
$('#stats').show();
$('#menuWrapper').animate({ bottom: '0px'}, 300)
.addClass("stats")
.addClass("open");
} else {
$('#menuWrapper').addClass("stats");
$('#sponsors').fadeOut();
$('#feedback').fadeOut();
$('#stats').fadeIn();
}
$('#menuWrapper').removeClass("sponsors")
.removeClass("feedback");
});
(this is an example of how I change the content. I have similar functions which change the content or minimize the menu depending on its current state.)
<div id="menuWrapper">
<div id="menuTop">
<a href="#" class="sponsors">Sponsors</a> | <a href="#" class="feedback">Feedback</a> | <a href="#" class="stats">Stats</a>
</div>
<div id="menuContent">
<div id="sponsors"></div>
<div id="feedback"></div>
<div id="stats"></div>
</div>
</div>
(and this is what the HTML looks like, before the content is dynamically loaded into the sponsors, feedback, and stats divs.)
To see an example of the funky functionality if necessary, see http://www.crowdsplat.com/alpha. If you have any insight into what may be causing this and/or how I can fix it, I'd greatly appreciate it. Thanks for your time.
Try return false from your click function or use event.preventDefault() to avoid the browser trying to follow the link which I assume is causing the jump to the top if you have an invalid bookmark e.g href="#"
e.g
$('a.stats').click(function(e) {
e.preventDefault();
if ($('#menuWrapper').hasClass("stats")) {
$('#menuWrapper').removeClass("stats")
.removeClass("open")
.animate({ bottom: '-100px'}, 300);
} else if (!$('#menuWrapper').hasClass("open")) {
$('#sponsors').hide();
$('#feedback').hide();
$('#stats').show();
$('#menuWrapper').animate({ bottom: '0px'}, 300)
.addClass("stats")
.addClass("open");
} else {
$('#menuWrapper').addClass("stats");
$('#sponsors').fadeOut();
$('#feedback').fadeOut();
$('#stats').fadeIn();
}
$('#menuWrapper').removeClass("sponsors")
.removeClass("feedback");
});
精彩评论