-1

I want jQuery code that triggers any function when user see specific content on web page

For example:

div{height:600px;background-color:#e3e3e3;}
#ghi{background-color:red;}
<div id="abc">
  hello
</div>
<div id="ghi">
  hello
</div>
<div id="xyz">
  hello
</div>

When i reach on id XYZ jquery trigger some function

And that function must fire only one, not repeated

  • you need something related to scroll offset and scroll top – Saksham Jun 09 '17 at 09:45
  • yes , i have edited my question . please check –  Jun 09 '17 at 09:49
  • What you need can be achieved searching in google, cant see any effort from your side. Check [this link, this was already answered HERE.](https://stackoverflow.com/questions/20791374/jquery-check-if-element-is-visible-in-viewport) – Foo Bar Jun 09 '17 at 09:49
  • Yahh, I have seen it but it continuously firing event and i want to fire event only once –  Jun 09 '17 at 10:22

1 Answers1

0

You need something like this

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop() + $(window).height(); //pixels to scroll to top + height of visible window
    var elemTop = $(elem).offset().top; //pixels of the top of element from the start of page
    return (elemTop <= docViewTop);
}
isScrolledIntoView("#xyz");

Use this in a combination of a local variable to fire only once;

var isFuncAlreadyFired = false;
$(window).scroll(function() {
    if(!isFuncAlreadyFired && isScrolledIntoView("#xyz"))
    {
        //fire custom function;
        isFuncAlreadyFired = true;
    }
});

This function will tell you whether the element supplied to the function is visible or not.

Though I would not suggest but you can also unbind the scroll event from the document once executed as

$(window).scroll(function() {
    if(isScrolledIntoView("#xyz"))
    {
        //fire custom function;
        $(document).unbind("scroll");
    }
});
Saksham
  • 8,110
  • 6
  • 35
  • 63