0

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

Community
  • 1
  • 1
Berklie
  • 361
  • 3
  • 8
  • 19

1 Answers1

2

jsFiddle Working Demo

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;
    }
});
Mohammad Adil
  • 43,337
  • 17
  • 86
  • 109
  • Nothing is happening in the jsFiddle that you posted (no alert is triggering). Can you please check your jsFiddle? Also, would your above code allow for the alert to trigger again once the element is shown again (after someone has scrolled all of the way down, and then back up again). I would like it to re-trigger if the element is re-visible. Thank you. – Berklie Apr 20 '13 at 21:28
  • Ok... all that I had to do was to edit "console.log" to "alert" and it worked. Let me test it on my site code and then come back to designate it as an answer. Thank you. – Berklie Apr 20 '13 at 21:31
  • with alert - http://jsfiddle.net/mohammadAdil/JnFqu/15/ ---- and yes if the element is shown again you will get alert --- will re-trigger. – Mohammad Adil Apr 20 '13 at 21:31
  • Thank you, I appreciate it. – Berklie Apr 20 '13 at 21:46