jQuery supports a variety of browser related events. The three common browser related events covered in this article are error, scroll, and resize.
The error event occurs when an element encounters an error such as if the element is not properly loaded. It is common to attach this event to image
elements. The scroll event occurs when the user scrolls in the specified element. This is useful if you want to trigger an event when the user
scrolls the document. Finally, the resize event is triggered when the browser window changes size.
Syntax
$(selector).error(function)
$(selector).scroll(function)
$(selector).resize(function)
Parameter | Description |
function | Specifies optional function to run |
HTML Example
We will use the following HTML for the examples listed below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// ... jQuery Code ...
});
</script>
</head>
<body>
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
Error
The error event is usually attached to image elements, that are referenced by a document and loaded by the browser. This event is triggered
if the element is not properly loaded. In the example below, the div contains an image that references an image source that does not exist. This
triggers an error event and the image is replaced with a div element.
<script type="text/javascript">
$("img").error(function(){
$("img").replaceWith(
"<div>Error loading image!</div>");
});
</script>
Scroll
The scroll event triggered when the user scrolls to a different place in the element. It applies to window objects, scrollable frames, and
elements with the overflow CSS property set to scroll.
<script type="text/javascript">
var a = 0;
$("div").scroll(function(){
$("span").text(++a)
});
</script>
Line1
Line2
Line3
Line4
Line5
Line6
Line7
Line8
Scrolled 0 times.
Resize
The resize event is triggered when the size of the browser window changes. Try resizing the browser window.
<script type="text/javascript">
$(window).resize(function(){
var a = 0;
$("span").text(++a)
});
</script>
The window has been resized 0 times.
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources