Rotan075 Rotan075 - 28 days ago 9
Javascript Question

Call function on scroll only once

I got a question regarding a function that will be called if the object is within my screen. But when the object is within my screen the function is been called and a alert is been fired. But if I close the alert and scroll further down the event is called again. I do not want that. How can I solve that?

Working example

My code so far:

<div id="wrapper">
scroll down to see the div
</div>
<div id="tester"></div>


JS

$(window).on('scroll',function() {
if (checkVisible($('#tester'))) {
alert("Visible!!!")
} else {
// do nothing
}
});

function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();

if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}


What I want is that the If function only will be called 1 time and not on every scroll if the object is visible.

Answer

Try using .one():

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

Or, unlink the event inside:

$(window).on('scroll',function() {
   // After Stuff
   $(window).off('scroll');
});

Guess you might need this code:

$(window).on('scroll',function() {
    if (checkVisible($('#tester'))) {
        alert("Visible!!!");
        $(window).off('scroll');
    } else {
        // do nothing
    }
});

Fiddle: http://jsfiddle.net/c68nz3q6/