Question

Have read that it is possible to detect a scroll with this line:

$('window').one('scroll', function() {  } );

If have this inline code:

var TimeVariable=setInterval(function(){ DoJQueryStuff() },300);

function DoJQueryStuff()
 {
 if(typeof jQuery == "undefined") return;
 window.clearInterval(TimeVariable);
 $('body').one('mousemove', function() { alert('mouse'); } );
 $('window').one('scroll', function() { alert('scroll'); } );
 }

DoJQueryStuff is called every 300 ms until JQuery is loaded. If I move the mouse anywhere on the screen, I got the "mouse" alert. If I scroll down I do NOT get the "scroll" alert. i.e. it's not firing.

Any help would be greatly appreciated.

David

Was it helpful?

Solution

first please use jquery ready http://api.jquery.com/ready/ method. i dont want to say your implementation is wrong but is slower than the jquery ready method.

your scroll function don't get executed basically because you are binding it to the wrong object. when you refer to the window object with jquery don't wrap it in apostrophs.

if you do so, jquery will intern call the document.getElementsByTagName and can't find the tagname window because window is not an child of the window.document node. so your scroll detect function never gets fired because jquery can't bind a eventListener to your submited element tagname.

simply bind it to window without apostrophs. this forces jquery to bind the scroll event directly to the window DOM object where your function is correctly fired on scroll.

Example:

$(window).ready(function(){
    $(this).one('mousemove', function() { 
        // mouse move
    }).one('scroll', function(){
        // scroll 
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top