Reputation: 590
This question is based off of this excellent StackOverflow element visibility detection script:
Check if element is visible after scrolling
Using the above script, I am able to properly detect when an element is visible on the page (by scrolling to it), to subsequently trigger an alert. The difference that I cannot appear to code from the above script, is that I would like the alert to trigger only once per time that the element is visible. With the below jsFiddle code, the alert continues to trigger with each and every scroll of the mouse or scrollbar while the element is visible:
http://jsfiddle.net/Berklie/JnFqu/
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function () {
var myelement = $('#overdueWarning');
if (isScrolledIntoView(myelement)) {
alert('Your book is overdue');
}
});
What I want is for the alert to trigger only once when the element becomes visible... and then again only if the element became invisible, then visible again.
Please let me know if I can offer anything else up. Thank you!
Berklie
Upvotes: 0
Views: 1647
Reputation: 44740
var shown = false;
$(window).scroll(function () {
var myelement = $('#overdueWarning');
if(isScrolledIntoView(myelement)){
if(!shown){
console.log('Your book is overdue');
}
shown = true;
}
else{
shown = false;
}
});
Upvotes: 2