jQuery Document/Window Events

When the user resizes or scrolls the browser window then the events triggers. Here are some jQuery methods to handle the document/ window events:

1) The ready() Method

JQuery ready() method is used to specify when a ready event occur. Ready even occurs after the document is ready. Syntax:
$(document).ready(function)

Example:

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script>  
$(document).ready(function(){  
    $("button").click(function(){  
        $("h1").slideToggle();  
    });  
});  
</script>  
</head>  
<body>  
<h1> This is the heading</h1>  
<p>This is the paragraph.</p>  
<button>Toggle between slide down and slide up for a p element.</button>  
</body>  
</html>
Try Now

2) The resize() Method

An event handler function is attached to an window element by the resize() method and that function is executed whenever the size of browser window changes. Syntax:
$(selector).resize()

Example:

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script>  
 x = 0;  
$(document).ready(function(){  
    $(window).resize(function(){  
        $("span").text(x += 1);  
    });  
});  
</script>  
</head>  
<body>  
<h2>Heading 1</h2>  
<p>This is the first paragraph.<span>0</span> times.</p>  
<p>Window resized <span>0</span> times.</p>  
<p>Try resizing your browser window.</p>  
</body>  
</html>
Try Now

3) The scroll() Method

The scroll event of jQuery occurs when the user scrolls in the specified element and then the scroll() method triggers the scroll event, or attaches a function to run.
$(selector).scroll()

Example:

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
<script>  
x = 0;  
$(document).ready(function(){  
    $("div").scroll(function(){  
        $("span").text( x+= 1);  
    });  
});  
</script>  
</head>  
<body>  
<p>Try the scrollbar in the div</p>  
<div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">   
If you cannot do great things, do small things in a great way.
Love has no age, no limit; and no death.</div>  
<p>Scrolled <span>0</span> times </p>  
</body>  
</html> 
Try Now