jQuery: Scroll the window then addClass() - how to callback
Inside a jQuery event handle开发者_JAVA技巧r, I would like to scroll the window and then add a class to something. This is my code:
$('#foo').click(function() {
window.scrollTo(y);
$('#bar').addClass('active');
});
$(window).scroll(function() {
$('#bar').removeClass('active');
});
Notice I have another handler to remove that same class whenever the window is scrolled. The scrolling part works fine, but seems to run asynchronously, so removeClass()
happens after addClass()
but before the scrolling is finished. I don't know how to do this in plain javascript. I know there is a jQuery scrollTop()
function that does the same thing (but seems to have cross-browser issues), but it doesn't accept a callback.
What I really need is a callback to add the class after the scrolling is finished. thanks!
You can also accomplish this with animate
$('#foo').click(function(){
var count = 0;
$('html,body').animate({scrollTop:0},1000,function(){
count++;
if (count == 2){
if (!($('#bar').hasClass('active'))){
$('.place').each(function(){
if($(this).hasClass('active')){
$(this).removeClass('active');
}
if($(this).attr('id') == 'bar'){
$(this).addClass('active');
}
});
}
}
});
});
EDIT:
give each possible place that you are "activating" a class. (e.g. 'place')
Then, the above code should work (edited)
This will scroll the browser to the top, taking 1000 miliseconds to do it, then add a class called "scrolled-top" to the BODY tag.
$('#foo').click(function(){
// Scroll window to top, taking 1000ms
$(window).animate({
// Animate these properties.
scrollTop : 0
},1000, function() {
// Animation complete callback.
$('body').addClass('scrolled-top');
});
}
If you were going to do this, you'd probably also want to add the class if the user manually scrolled to the top, but also remove the "scrolled-top" class while scrolling down. If so, then this would be the complete function:
// On page load, add class as window will start at the top
$('body').addClass('scrolled-top');
// Add class to body when window is scrolled to top
$(window).scroll(function () {
var scrollAmount = $(window).scrollTop();
if(scrollAmount > 0) {
$('body').removeClass('scrolled-top');
} else {
$('body').addClass('scrolled-top');
}
}
// Scroll window to top, taking 1000ms
$('#foo').click(function(){
$(window).animate({
// Animate these properties.
scrollTop : 0
},1000);
}
Notice that with the complete function you don't even need the callback.
There is a jQuery plugin called scrollTo that provides this capability (along with other features). I recommend using this plugin (check out the onAfter
callback config) or check it's source.
精彩评论