Did you find this useful?
Socialize it today.


jQuery Browser Events

Friday, June 29, 2012

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)


ParameterDescription
functionSpecifies 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> 


Error loading image!


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.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor JavaScript and jQuery: The Missing Manual Pro jQuery