22

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
}
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
user2152326
  • 279
  • 1
  • 3
  • 7

3 Answers3

119

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"))
});
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
23

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});
SachinGutte
  • 6,947
  • 5
  • 35
  • 58
4

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

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

scroll:

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

or bind all event in one function

$(window).on("load scroll resize",function(e){
bipen
  • 36,319
  • 9
  • 49
  • 62