Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 } 
like image 644
user2152326 Avatar asked Mar 27 '13 17:03

user2152326


People also ask

How does jQuery determine window resize?

$(window). on('resize', function(){ var win = $(this); //this = window if (win. height() >= 820) { /* ... */ } if (win.

What happens when the window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

What is window load in jQuery?

The code which gets included inside $( window ). on( "load", function() { ... }) runs only once the entire page is ready (not only DOM). Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0.


1 Answers

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")) }); 
like image 78
mattytommo Avatar answered Oct 13 '22 13:10

mattytommo