Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  95] [ 2]  / answers: 1 / hits: 44263  / 9 Years ago, fri, august 21, 2015, 12:00:00

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.


More From » jquery

 Answers
2

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:


// this will check if element is in viewport

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;
}

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

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


[#65345] Wednesday, August 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiejarretk

Total Points: 612
Total Questions: 103
Total Answers: 88

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;