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.



functionSpecifies optional function to run

HTML Example

We will use the following HTML for the examples listed below.

<!DOCTYPE html>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
      // ... jQuery Code ...
  <div id="div1"> <!-- Some Content --> </div>


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">
       "<div>Error loading image!</div>");

Error loading image!


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;

Scrolled 0 times.


The resize event is triggered when the size of the browser window changes. Try resizing the browser window.

<script type="text/javascript">
   var a = 0;

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

Professional jQuery Pro jQuery HTML CSS and JavaScript Editor