user2152326 user2152326 - 4 months ago 38
Javascript Question

Run Jquery function on window events: load, resize, and scroll?

How do I run a jquery function on window events: load, resize, and scroll?

Here is my code
I'm trying to detect if a div is viewable and then if it is run some ajax code...




<script>
function topInViewport(element) {
return $(element).offset().top >= $(window).scrollTop() && $(element).offset().top <= $(window).scrollTop() + $(window).height();
}

</script>

<script>
topInViewport($("#mydivname"))
{
// ajax code goes here
}

Answer

You can use the following. They all wrap the window object into a jQuery object.

Load:

$(window).load(function () {
    topInViewport($("#mydivname"))
});

Resize:

$(window).resize(function () {
   topInViewport($("#mydivname"))
});

Scroll

$(window).scroll(function () {
    topInViewport($("#mydivname"))
});

Or bind to them all using on:

$(window).on("load resize scroll",function(e){
    topInViewport($("#mydivname"))
});