JQuery: How can I use a timeout script to detect the page scroll?
I'm wondering how I can make a timeout script to detect when the scrolltop() is <= to pos.top && menu.hasClass('fixed')) so the menu can return to default.
$(function(){
var menu = $('#menu'),
pos = menu.offset();
$(window).scroll(function(){
if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){
menu.fadeOut('fast', function(){
$(this).removeClass('default').addClass('fixed').fadeIn('fast');
});
} else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
开发者_运维问答 menu.fadeOut('fast', function(){
$(this).removeClass('fixed').addClass('default').fadeIn('fast');
});
}
});
});
usually you wouldn't detect this issue with this script, but the way I have my site set up with JavaScript to update the div tag's content the menu doesn't notice the page content increased or decreased in height or width (depending on situation) and you can't scroll so the menu stays where it is at the top of the page.
This is not a new problem, check out this tutorial where they run through the HTML, CSS(3) and the jQuery required - http://www.1stwebdesigner.com/tutorials/create-stay-on-top-menu-css3-jquery/
EDIT:
From reading the above comments it looks like you may wish to detect inactivity, and then scroll the user to the top of the page. This makes the problem more interesting.
$(function(){
var menu = $('#menu'),
pos = menu.offset();
var timer = setTimeout('scrollToTop()', 30000);
$(window).scroll(function(){
// scrolling has happened, reset any timers
clearTimeout(timer);
timer = setTimeout('scrollToTop()', 30000);
if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){
menu.fadeOut('fast', function(){
$(this).removeClass('default').addClass('fixed').fadeIn('fast');
});
} else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){
menu.fadeOut('fast', function(){
$(this).removeClass('fixed').addClass('default').fadeIn('fast');
});
}
});
});
// if 30 seconds elapses with no scrolling scroll to top
function scrollToTop() {
window.scroll(0,0);
}
精彩评论