jQuery Events

An event can be thought of as some action taken on a web page. This may be due to user interaction, such as clicking the mouse, entering data into a form field or submitting the form. Events can also occur independently of the user, for instance, when the page loads and unloads.

Events are handled by event handlers. An event handler can be attached to an HTML element on the page, and is registered to handle that particular event for that element.

Event handlers are typically javascript functions that will be executed each time the event is triggered.

jQuery provides many methods for event handling and numerous properties that can be accessed from the Event Object. This page includes most of methods and properties, but specifically excludes the deprecated methods.

Examples

The .focus() and .blur() methods

The focus event occurs when an element gains focus, and the .focus() method is used to handle or trigger this event.

Form elements and links receive the focus event. Other elements can receive the focus event if their tab index attribute has been set ( and if using a modern browser ).

The method has the following syntax:

  1. $( selector ).focus()
  2. $( selector ).focus( function( eventObject ) )
  3. $( selector ).focus( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The blur event occurs when an element loses focus, and the .blur() method is used to handle or trigger this event.

The method has the following syntax:

  1. $( selector ).blur()
  2. $( selector ).blur( function( eventObject ) )
  3. $( selector ).blur( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Trigger the focus event for the element txtInput.

$('input#txtInput').focus();

When the element txtInput loses focus, store its value in the variable txt, and display this value in the element txtPara.

$('input#txtInput').blur(function () {
 var txt = $(this).val()
 $('p#txtPara').text(txt);
});

The .blur() method bound to the input element defineColor uses the eventData parameter to store a string of text. The value entered into the input is stored in the variable color. The string of text is retrieved from the eventObject.data property using the key Question, the color value is appended, and the result is shown in the paragraph element showFavouriteColor.

var txt = 'Your favourite color is:';
$('input#defineColor').blur({ Question: txt }, function (eventObject) {
 var color = $(this).val();
 $('p#showFavouriteColor').html(eventObject.data.Question + ' ' + color);
});
Top

The .focusin() and .focusout() methods

The focusin event occurs when an element, or one of its descendant elements, gain focus.

The method has the following syntax:

  1. $( selector ).focusin( function( eventObject ) )
  2. $( selector ).focusin( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The focusout event occurs when an element, or one of its descendant elements, lose focus.

The method has the following syntax:

  1. $( selector ).focusout( function( eventObject ) )
  2. $( selector ).focusout( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Set a tab index for the element inputDiv. If inputDiv or any child element gets focus, append the event.target.tagName property to inputDiv.

document.getElementById('inputDiv').tabIndex = '0';
$('div#inputDiv').focusin(function (event) {
 $(this).append('<div>The event.target.tagName property is: ' + event.target.tagName + '</div>');
});

Set a tab index for the element inputDiv. If inputDiv or any child element loses focus, append the event.target.nodeName property to inputDiv.

document.getElementById('inputDiv').tabIndex = '0';
$('div#inputDiv').focusout(function (event) {
 $(this).append('<div>The event.target.nodeName property is: ' + event.target.nodeName + '</div>');
});
			
Top

The .change() method

The .change() method is used to bind an event handler to the change event for the selected element, or to trigger the event on the selected element. The change event applies only to input elements, textarea boxes and select elements. These elements receive the change event when their value changes.

A selection made in a select box, checkbox or radio button will trigger the event immediately. For other elements, the event is triggered when the element loses focus.

The method has the following syntax:

  1. $( selector ).change()
  2. $( selector ).change( function( eventObject ) )
  3. $( selector ).change( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Bind an event handler to the change event for the radio buttons which have a name attribute pizzaToppings. Store the value of the radio button that triggered the change event in the topping variable. Display a message box confirming whether to order the selected topping.

$('input[name=pizzaToppings]:radio').change(function () {
 var topping = $(this).val();
 confirm('Do you want to order the following pizza topping?' + ' ' + topping);
});
Top

The .click() method

The .click() method binds an event handler to the click event for the selected element. It can also be used to trigger the event on a selected element.

The method has the following syntax:

  1. $( selector ).click()
  2. $( selector ).click( function( eventObject ) )
  3. $( selector ).click( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Use the setInterval() method to call the function startTimedEvent() every five seconds. The startTimedEvent() function triggers the click event for the input element annoyingBtn. The event handler for the click event appends a string of text to a div element with the class name left. A counter is incremented on each call to the function and if its value is five the timed event is stopped with the clearInterval() method.

var stop = setInterval(startTimedEvent, 5000);
var i = 0;
$('input#annoyingBtn').click(function () {
 $('div.left').append('<p>THIS IS RATHER ANNOYING TEXT!</P>')
 if (i == 5) {
  clearInterval(stop);
 }
 i++;
});

function startTimedEvent() {
 $('input#annoyingBtn').click();
}
Top

The .error() method

The .error() method binds an event handler to the error event for the selected element. An element receives the error event if it was not loaded correctly.

The method has the following syntax:

  1. $( selector ).error( function( eventObject ) )
  2. $( selector ).error( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The event handler must be bound to the error event before the browser fires the event.

Bind an event handler to the error event for the image element badImg. Specify a non-existent url as the source attribute for the image. When the browser loads the page the alert message will be displayed.

$('#badImg').error(function () {
 alert('The image failed to load');
}).attr('src', 'nonExistent.jpg');
Top

The event.currentTarget property.

The currentTarget property of the Event Object will return the current DOM element within the event bubbling phase.

The syntax is: event.currentTarget

Event handlers have been bound to the click event for the document, body, and an image element. The image element is the innermost element and clicking on the image will fire its click event handler. The node name within the currentTarget property of the Event Object is retrieved and appended to the body. The event bubbles up to the next element that has a registered click event handler, firing the body's click event handler and displaying the currentTarget's node name. The event then continues its bubbling phase up the DOM tree to the document and fires its click event handler, also displaying the node name for the currentTarget. The text appended to the body will be IMG clicked, BODY clicked, and #document clicked in that order.

$(document).click(function (event) {
 $('body').append('<p>' + event.currentTarget.nodeName + ' ' +  'clicked</p>')
});

$('body').click(function (event) {
 $('body').append('<p>' + event.currentTarget.nodeName + ' ' + 'clicked</p>')
});

$('img').click(function (event) {
 $('body').append('<p>' + event.currentTarget.nodeName + ' ' + 'clicked</p>')
});
Top

The event.data property.

The event.data property of the Event Object is an optional map of key/value pairs, passed to the event handler when the handler is bound to the event.

The syntax is: event.data

When the browser loads the page, the href attribute of each anchor tag on the page is stored in the hrefArray array. An event handler is bound to the click event for each of the anchor tags. The first parameter to the .click() method is eventData which has the key name, value. This passes the hrefArray array to the event handler's Event Object. When an anchor is clicked a call is made to event.preventDefault() to prevent the clicked anchors from navigating to a new URL. A new div element with an id pageHref and containing a string of text, is added as the child of the div element hrefContainer. The event.data property is used to get the length of the hrefArray array, and a for loop is created that iterates over each item in the array. The href attribute of each anchor tag is retrieved from the array using the event.data property and added to a new div element which is then appended to the pageHref div element.

var hrefArray = [];
$('a').each(function () {
 var href = $(this).attr('href');
 hrefArray.push(href);
});

$('a').click({ value: hrefArray }, function (event) {
 event.preventDefault();
 $('div#hrefContainer').html('<div id="pageHref">The href attribute for each of the anchor tags on this page is:</div>')

 for (i = 0; i < event.data.value.length; i++) {
  $('div#pageHref').append('<div>' + event.data.value[i] + '</div>');
 }
});
Top

The event.delegateTarget property.

The delegateTarget property of the Event Object returns the element that is attached to the event handler currently handling the event. Event delegation utilizes event bubbling, binding an event handler to an element's ancestor rather than the element itself. In these cases the delegateTarget property will be the element's ancestor. If an event handler is bound to the element itself rather than an ancestor, the delegateTarget property will be equal to the currentTarget property.

The syntax is: event.delegateTarget

Bind a delegated event handler to the hover event for all div elements which have the class name sepia. Pass p in as the second argument to the .on() method to filter for all paragraph elements that are descendants of div.sepia. The event.delegateTarget property will be the element div.sepia that is attached to the event handler currently handling the hover event, and this is used as a selector to toggle the class sepiaTone. .

$('div.sepia').on('hover', 'p', function (event) {
   $(event.delegateTarget).toggleClass('sepiaTone');
});

Bind delegated event handlers, using an events-map, to the mouseenter and mouseleave events for all div elements with the class name sepia. Pass p in as the second argument to the .on() method to filter for all paragraph elements that are descendants of div.sepia. The event.delegateTarget property is used to change the background color and font color of the element div.sepia that is attached to the event handler currently handling the mouseenter event. Finally, the event.delegateTarget property is used as a selector to remove the previous styling of the element div.sepia that is attached to the event handler currently handling the mouseleave event.

$('div.sepia').on({
 'mouseenter': function (event) {
   $(event.delegateTarget).css({ 'backgroundColor': '#5E2612', 'color': '#FFC125' });
 },
 'mouseleave': function (event) {
   $(event.delegateTarget).css({ 'backgroundColor': '', 'color': '' });
 }
}, 'p');
Top

The event.pageX and event.pageY properties.

The event.pageX property returns the mouse coordinates relative to the left edge of the document.

The syntax is: event.pageX

The event.pageY property returns the mouse coordinates relative to the top edge of the document.

The syntax is: event.pageY

Bind an event handler to the mousemove event for the document. Display the event.pageX and event.pageY properties in the div element mousePosition.

$(document).on('mousemove', function (event) {
   $('div#mousePosition').text('event.pageX: ' + event.pageX + ', event.pageY: ' + event.pageY);
});
Top

The event.preventDefault() method.

This method prevents the default action of the event.

The syntax is: event.preventDefault()

Bind an event handler to the click event for the submit button submitPage. Call event.preventDefault() to prevent the button from submitting the page. If the value of the input element nameDetails is not an empty string, submit form1. If the value is an empty string, display an alert dialog box.

$('input#submitPage').click(function (event) {
 event.preventDefault();
 if ($('input#nameDetails').val() != '') {
   document.forms['form1'].submit();
 } else {
   alert('Please enter your name');
 }
});
Top

The event.relatedTarget property

The event.relatedTarget property is commonly used with the mouseover and mouseout events. It returns the other element involved in the event. The relatedTarget property for the mouseover event is the element that has been exited, and for the mouseout event is the element that has been entered. The relatedTarget property can also be used with Internet Explorer's proprietary mouseenter and mouseleave events, which are simulated by jQuery allowing them to be used in any browser.

The syntax is: event.relatedTarget

Bind event handlers to the mouseover and mouseout events for all paragraph elements on the page. Display the tag name of the event.relatedTarget property for the current mouseover and mouseout event in the div element displayRelatedTarget.

$('p').on({
'mouseover': function (event) {
   $('div#displayRelatedTarget').text('event.relatedTarget for mouseover: ' + event.relatedTarget.tagName);
},
'mouseout': function (event) {
   $('div#displayRelatedTarget').text('event.relatedTarget for mouseout: ' + event.relatedTarget.tagName);
}
});
Top

The event.stopImmediatePropagation() method.

The event.stopImmediatePropagation() method prevents the execution of other event handlers bound to the same event and the same element. It will also prevent the event from bubbling to elements higher in the DOM tree.

The syntax is: event.stopImmediatePropagation()

Bind two event handlers to the click event for all input elements which have the class name btn. Next bind an event handler to the click event for a div element with the id container ( which is higher in the DOM tree than input.btn ). The first click event handler, attached to input.btn, calls event.stopImmediatePropagation(). This prevents the execution of the second click event handler attached to this element. The event will no longer bubble up the DOM tree, and the handler bound to the click event for the element container will not be executed. The text Apples is displayed in the element displayResult when input.btn is clicked. The click event handler for container will still execute normally when clicked independently, changing its background color to red.

$('input.btn').click(function (event) {
 event.stopImmediatePropagation();
 $('div#displayResult').text('Apples');
});

$('input.btn').click(function (event) {
 $('div#displayResult').text('Oranges');
});

$('div#container').click(function () {
 $(this).css('background-color', 'Red');
});
Top

The event.stopPropagation() method.

The event.stopPropagation() method prevents an event from bubbling up the DOM tree.

The syntax is: event.stopPropagation()

Bind two event handlers to the click event for all input elements which have the class name btn. Next bind an event handler to the click event for a div element with the id container ( which is higher in the DOM tree than input.btn ). The first click event handler, attached to input.btn, calls event.stopPropagation(). Clicks on input.btn will execute both of its click event handlers, displaying the text Oranges in the div element displayResult. The event will no longer bubble up the DOM tree, and the handler bound to the click event for the element container will not be executed. The click event handler for container will still execute normally when clicked independently, changing its background color to red.

$('input.btn').click(function (event) {
 event.stopPropagation();
 $('div#displayResult').text('Apples');
});

$('input.btn').click(function (event) {
 $('div#displayResult').text('Oranges');
});

$('div#Container').click(function () {
 $(this).css('background-color', 'Red');
});
Top

The event.target property.

The event.target property is the element that triggered the event. This may be the same element that the event was assigned to, or a different element.

The syntax is: event.target

Bind an event handler to the click event for the body element. When the body or any descendent element is clicked, retrieve that element's tag name from the event.target property, and display it in a paragraph appended to the div element.

$('body').click(function (event) {
 $('div').append("<p>The event.target property's tag name is: " + event.target.tagName + "</p>");
});
Top

The .hover() method.

The .hover() method is used to bind event handlers for the mouseenter and mouseleave events.

The method has the following syntax:

  1. $( selector ).hover( functionIn( eventObject ), functionOut( eventObject ) )
  2. $( selector ).hover( functionInOut( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The functionIn event handler is bound to the mouseenter event, and the functionOut event handler is bound to the mouseleave event. The functionInOut event handler is bound to both the mouseenter and mouseleave events, and will fire when the mouse pointer enters and leaves an element.

Bind event handlers to the mouseenter and mouseleave events for all paragraph elements. When the mouse pointer enters a paragraph, change its background color to yellow. When the mouse pointer leaves a paragraph, remove the background color.

$('p').hover(
function () {
 $(this).css('background-color', 'yellow');
}, function () {
 $(this).css('background-color', '');
});

Bind a single event handler to the mouseenter and mouseleave events for all paragraph elements. If the event.type property is mouseenter, change the currently selected paragraph's color to yellow. If the event.type property is mouseleave, remove the background color from the currently selected paragraph.

$('p').hover(function (event) {
var eventType = event.type;
if (eventType == 'mouseenter') {
 $(this).css('background-color', 'yellow');
} else if (eventType == 'mouseleave') {
 $(this).css('background-color', '');
} 
});
Top

The .keydown(), .keyup() and .keypress() methods.

An element that has focus will receive the keydown event if a key is pressed on the keyboard. The .keydown() method is used to bind an event handler to the keydown event, or to trigger the event on the selected element. It is typically used with form elements.

The method has the following syntax:

  1. $( selector ).keydown()
  2. $( selector ).keydown( function( eventObject ) )
  3. $( selector ).keydown( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

An element that has focus will receive the keyup event if a key on the keyboard is pressed and released. The .keyup() method is used to bind an event handler to the keyup event, or to trigger the event on the selected element. It is typically used with form elements.

The method has the following syntax:

  1. $( selector ).keyup()
  2. $( selector ).keyup( function( eventObject ) )
  3. $( selector ).keyup( eventData, function( eventObject ) )

The parameters are identical to the .keydown() method.

An element that has focus will receive the keypress event if a key is pressed on the keyboard. If a key is pressed and held down, the number of keypress events triggered will be equal to the number of inserted characters. This differs from the keydown event which would only be triggered once. The .keypress() method is used to bind an event handler to the keypress event, or to trigger the event on the selected element. It is typically used with form elements. The .keypress() method can produce some inconsistencies across browsers. For example the delete key has the key code 46, but the .keypress() method will return 0 with some browsers, while others don't return any value.

The method has the following syntax:

  1. $( selector ).keypress()
  2. $( selector ).keypress( function( eventObject ) )
  3. $( selector ).keypress( eventData, function( eventObject ) )

The parameters are identical to the .keydown() method.

Bind an event handler to the keydown event for the element txtInput. Use the event.which property to retrieve the key code of the key pressed, and display this in the txtLbl element.

$('input#txtInput').keydown(function (event) {
 $('label#txtLbl').text('The key pressed has the key code: ' + event.which);
});

Bind an event handler to the keyup event for the element txtInput. Display the text entered in txtInput inside a label with an id txtLbl.

$('input#txtInput').keyup(function () {
 $('label#txtLbl').text($(this).val());
});

Bind an event handler to the keypress event for the element txtInput. Use the event.which property to retrieve the key code of the key pressed, and display this in the txtLbl element.

$('input#txtInput').keypress(function (event) {
 $('label#txtLbl').text('The key pressed has the key code: ' + event.which);
});
Top

The .load() method.

An element containing a URL will receive the load event when it and its children have fully loaded. Elements that receive the load event are images, scripts, frames, iframes, and the window object. The .load() method can be used instead of the document.ready() method, and may be needed if it is necessary to wait until all the images on the page have been fully loaded. Using the .ready() method is quicker and more preferable if the code can be executed sooner.

The method has the following syntax:

  1. $( selector ).load( function( eventObject ) )
  2. $( selector ).load( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Bind an event handler to the load event for the window. Show an alert dialog displaying the HTML contents of the descriptionLbl element.

$(window).load(function () {
 alert($('label#descriptionLbl').html());
});
Top

The .mousedown() and .mouseup() methods.

The .mousedown() method is used to bind an event handler to the mousedown event or to trigger the event on the selected element.

The method has the following syntax:

  1. $(selector ).mousedown()
  2. $( selector ).mousedown( function( eventObject ) )
  3. $( selector ).mousedown( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The .mouseup() method is used to bind an event handler to the mouseup event or to trigger the event on the selected element.

The method has the following syntax:

  1. $( selector ).mouseup()
  2. $( selector ).mouseup( function( eventObject ) )
  3. $( selector ).mouseup( eventData, function( eventObject ) )

The parameters are identical to the .mousedown() method.

Bind an event handler to the mousedown event, and an event handler to the mouseup event, for an image element with the id wetherlam. On mousedown apply a black border to the image and remove it on mouseup.

$('img#wetherlam').mousedown(function () {
 $(this).css('border', '3px solid black');
}).mouseup(function () {
 $(this).css('border', '');
});
Top

The .mouseover() and .mouseout() methods.

The .mouseover() method is used to bind an event handler to the mouseover event or to trigger the event on the selected element.

The method has the following syntax:

  1. $( selector ).mouseover()
  2. $( selector ).mouseover( function( eventObject ) )
  3. $( selector ).mouseover( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The .mouseout() method is used to bind an event handler to the mouseout event or to trigger the event on the selected element.

The method has the following syntax:

  1. $( selector ).mouseout()
  2. $( selector ).mouseout( function( eventObject ) )
  3. $( selector ).mouseout( eventData, function( eventObject ) )

The parameters are identical to the .mouseover() method.

Bind an event handler to the mouseover event, and an event handler to the mouseout event for all paragraph elements. Change the background color of the current paragraph on mouseover to yellow, and remove the color on mouseout.

$('p').mouseover(function () {
 $(this).css('background-color', 'yellow');
}).mouseout(function () {
 $(this).css('background-color', '');
});
Top

The .mouseenter() and .mouseleave() methods.

Internet Explorer uses these two proprietary events, which jQuery simulates to allow them to be used in all browsers. A great advantage of these events is that they do not bubble up the DOM tree, and the event handlers for the mouseenter and mouseleave events are only triggered by the elements they are bound to.

The .mouseenter() method binds an event handler to the mouseenter event or triggers that event on a selected element.

The method has the following syntax:

  1. $( selector ).mouseenter()
  2. $( selector ).mouseenter( function( eventObject ) )
  3. $( selector ).mouseenter( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

The .mouseleave() method binds an event handler to the mouseleave event or triggers that event on a selected element.

The method has the following syntax:

  1. $( selector ).mouseleave()
  2. $( selector ).mouseleave( function( eventObject ) )
  3. $( selector ).mouseleave( eventData, function( eventObject ) )

The parameters are identical to the .mouseenter() method.

Bind an event handler to the mouseenter event, and an event handler to the mouseleave event, for an image element with the id fells. ( The default width of the image is 30%. ) Change the width of the image to 70% on mouseeenter, and 30% on mouseleave.

$('img#fells').mouseenter(function () {
 $(this).css('width', '70%');
}).mouseleave(function () {
 $(this).css('width', '30%');
});
Top

The .mousemove() method.

The .mousemove() method binds an event handler to the mousemove event or triggers that event on a selected element.

The method has the following syntax:

  1. $( selector ).mousemove()
  2. $( selector ).mousemove( function( eventObject ) )
  3. $( selector ).mousemove( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Bind an event handler to the mousemove event for the body. When the mouse pointer moves inside an element, display the event.target.nodeName property in the label displayLbl.

$('body').mousemove(function (event) {
 $('label#displayLbl').text('The event.target.nodeName property is: ' + event.target.nodeName );
});
Top

The .on() and .off() methods.

The .on() method binds an event handler to one or more events for the selected element.

The method has the following syntax:

  1. $( selector ).on( events, selectorFilter, eventData, function( eventObject ) )
  2. $( selector ).on( events-map, selectorFilter, eventData )

The events parameter is one or more space-separated event types. Namespaces can be added to the event types as an aid to later identification. Providing namespaces makes it possible to remove or trigger an element's event handler for a particular event, without removing or triggering event handlers bound to the same event for other elements.

The selectorFilter parameter is optional, but if provided must be a descendant of the selected element that the .on() method is attached to. If a selectorFilter parameter is not provided, the method's event handler will fire every time the event is passed to the selected element. If a selectorFilter parameter is provided, the event handler will not fire for events occurring directly on the selected element, but fires only on descendant elements that match the selectorFilter ( starting at the innermost element and bubbling up the DOM tree to the selected element ).

The eventData parameter is optional and can be any type, but recommended practice is to pass a map of data using key/value pairs.

The eventObject parameter is optional, and contains properties that give information about the event.

The events-map parameter consists of key/value pairs. The key is a strings of event types separated by a space, and can include namespaces. The value is an event handler, or optionally the value false can be given in place of the handler to cancel the default action of the event and to stop event propagation.

The .off() method is used to remove event handlers that were attached using the .on() method. The arguments provided to the .off() method must match exactly those provided to the .on() method.

The method has the following syntax:

  1. $( selector ).off( events, selectorFilter, function( eventObject ) )
  2. $( selector ).off( events-map, selectorFilter )

The events parameter is one or more space-separated event types. Namespaces can be included if they were initially appended to the .on() method's events parameter. It is also possible to pass the namespace in as a parameter without including the event type. Using namespaces helps to isolate the event handlers and remove them for a particular event.

The selectorFilter parameter is used to remove delegated event handlers, and should match the one provided to the .on() method. Passing ** as the parameter will remove all the delegated events from an element.

The eventObject parameter is optional, and contains properties that give information about the event.

The events-map parameter is the key/value pairs object passed to the .on() method.

Bind an event handler to the click event for the alertBtn, and display a dialog when the button is clicked.

$('input#alertBtn').on('click', function () {alert('Button Clicked')});

Store a sequence of numbers in a variable. Bind a delegated event handler to the click event, and attach it to the body element. Pass the delegatedBtn element into the method as the selectorFilter parameter. Pass the variable sequence into the method as data for the event handler. Clicking delegatedBtn retrieves the value from the event.data.numbers property, displaying 12345 in the alert dialog box.

var sequence = '12345';
$('body').on('click', 'input#delegatedBtn',{numbers:sequence}, function (event) {
 alert(event.data.numbers)
});

Bind an event handler to the click event and the mouseout event for all paragraph elements. When the currently selected paragraph is clicked or receives the mouseout event, change its background color to blue.

$('p').on('click mouseout', function () {
 $(this).css('background-color','blue');
});

Bind delegated event handlers, using an events-map, to the mouseover and mouseout events, and attach these to the body element. Pass p in as the selectorFilter parameter to represent all paragraph elements that will trigger the event handlers. Pass a color value in as the method's data parameter using a key/value pair. When the mouse moves over a paragraph element, use the key ( color ) to retrieve the color value from the event.data property, and change the paragraph's background color to red. When the mouse moves out of the paragraph, remove the background color.

$('body').on({
'mouseover': function (event) {
  $(this).css('background-color', event.data.color);
 },
 'mouseout': function (event) {
  $(this).css('background-color', '');
 }
}, 'p', { color: 'red' });

Use an events map to bind event handlers to the mouseover event, and the mouseout event. Attach the event handlers to all paragraph elements. Within the mouseover event handler, change the currently selected paragraph's background color to green. Within the mouseout event handler, remove the background-color.

Use an events-map to bind event handlers to the mouseover event and the mouseout event, giving both events the namespace fontColor. Attach the event handlers to all paragraph elements. Within the mouseover event handler change the currently selected paragraph's font color to red. Within the mouseout event handler, remove the font color style.

Bind an event handler to the click event for the button element changeStyle. When the button is clicked, remove all event handlers for events, which have the namespace fontColor, from all paragraph elements.

$('p').on({
 'mouseover': function () {
  $(this).css('background-color', 'green');
 },
  'mouseout': function () {
  $(this).css('background-color', '');
 }
});

$('p').on({
 'mouseover.fontColor': function () {
  $(this).css('color', 'red');
 },
'mouseout.fontColor': function () {
  $(this).css('color', '');
 }
});

$('input#changeStyle').on('click', function () {
 $('p').off('.fontColor');
});
Top

The .one() method.

The .one() method binds an event handler to an event, that will execute once per selected element.

The method has the following syntax:

  1. $( selector ).one( events, eventData, function( eventObject ) )
  2. $( selector ).one( events, selectorFilter, eventData, function( eventObject ) )
  3. $( selector ).one( events-map, selectorFilter, eventData )

The events parameter is a string of space-separated event types. Namespaces can be added to the event types and custom event names can be given. The eventData parameter is an optional map of data that will be passed to the event handler in the event object. The eventObject parameter is optional, and contains properties that give information about the event. The selectorFilter is optional, but must be a descendant of the element the handler is attached to. If given, the selctorFilter element will trigger calls to the event handler. The events-map parameter has a key and a value. The key is a space-separated string of event types ( optionally including namespaces ), and the value is the event handler.

Bind an event handler to the click event for all paragraph elements. Show a message the first time each paragraph on the page is clicked.

$('p').one('click', function () {
 alert('Only one click per paragraph is allowed !');
});
Top

The jQuery.proxy() method.

The jQuery.proxy() method is used to set the context of a function, and returns a new function, setting the keyword this equal to the context provided.

The method has the following syntax:

  1. $( selector ).event( jQuery.proxy( function, context ) )
  2. $( selector ).event( jQuery.proxy( context, name ) )

The function parameter names the function for which the context will be changed.

The context of the function will be changed to the object provided as the context parameter

The name parameter is the name of the function for which the context will be changed.

An object is created which has a property and two methods. Clicking the input#withoutProxyBtn button calls the showContext function. The keyword this is used to represent the HTML element currently handling the event which will be the input#withoutProxyBtn button. The button does not have a property named stringValue and so the alert returns undefined. The method unbindContext is not a function of the button and so the method will not be called.

Clicking the input#withProxyBtn also calls the showContext method but this time, the context of the function has been changed to the test object. The keyword this now represents the test object which does contain the property stringValue, and the alert returns "This is the string value for the object" as expected. The unbindContext method is now called, unbinding the event handler (showContext) for the click event, again using this to represent the test object.

var test = {
 stringValue: "This is the string value for the object",
 showContext: function () {
  alert(this.stringValue);
  this.unbindContext();
 },

 unbindContext: function () {
  $("input#withProxyBtn").unbind("click", this.showContext);
 }
};

$('input#withoutProxyBtn').click(test.showContext);
$('input#withProxyBtn').click($.proxy(test.showContext, test));
Top

The .ready() method.

The event handler bound to the ready event is executed when the DOM is fully loaded. This makes it a safe place in which to place other event handlers and code.

The .ready() method should not be used with body's onload attribute. Style sheets must be referenced on the page before the ready event handler, if the styles are manipulated by the code contained within the event handler. More detailed information covering the .ready() method can be found here.

The method has the following syntax:

  1. $( document ).ready( function() )
  2. jQuery( document ).ready( function() )
  3. $( function() )

Although the syntax of the three methods is slightly different, they all provide the equivalent functionality.

Bind an event handler to the ready event, using the shortcut version of the .ready() method. Retrieve the title attribute for an anchor tag with the id homePage. Display the title attribute in an alert dialog.

$(function () {
 var title = $('a#homePage').attr('title');
 alert('The title attribute of the link is: ' + title);
});
Top

The .resize() method

The resize event is sent to the window element when browser's window changes size, and the .resize() method is used to handle or trigger this event.

The method has the following syntax:

  1. $( window ).resize()
  2. $( window ).resize( function( eventObject ) )
  3. $( window ).resize( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Store a reference to the body element in a variable. Bind an event handler to the resize event for the window. When the size of the browser's window changes, store references to the width and height of the window, and display these values in a div element. When the resize event is sent to the window, change the background color of the body according to the window's width.

var bodyEl = $('body');
$(window).resize(function (event) {
 var width = $(window).width();
 var height = $(window).height();
 $('div#dimensionsDiv').html('Window width: ' + width + ' ' + ' Window height: ' + height);
 if (width >= 1200) {
  bodyEl.css('background-color', 'red');
 }
 else if (width > 800 && width < 1200) {
  bodyEl.css('background-color', 'orange');
 }
 else if (width <= 800) {
  bodyEl.css('background-color', 'green');
 }
});
Top

The .scroll() method.

An element with scroll bars receives the scroll event when the position of a scrollbar is changed, and the .scroll() method is used to handle or trigger this event.

The method has the following syntax:

  1. $( selector ).scroll()
  2. $( selector ).scroll( function( eventObject ) )
  3. $( selector ).scroll( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Bind an event handler to the scroll event for the scrollableDiv element. When the element is scrolled display its scroll top and scroll left position in the scrollPosDiv element.

$('div#scrollableDiv').scroll(function (event) {
 $('div#scrollPosDiv').html('scroll top is: ' + $(this).scrollTop() + ' scroll left is: ' + $(this).scrollLeft());
});
Top

The .select() method.

The select event is sent to text input elements and textarea elements when the text they contain is selected. The .select() method is used to handle or trigger this event.

The method has the following syntax:

  1. $( selector ).select()
  2. $( selector ).select( function( eventObject ) )
  3. $( selector ).select( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Bind an event handler to the select event for all input elements which have a type attribute equal to text. If the element has text selected, display its id in a label. Add two labels as children of the selectedIdDiv element using the .html() method.

$('input[type="text"]').select(function () {
 $('div#selectedIdDiv').html('<label>Text has been selected:<label> <br/> <label style="padding:0 10px">input id: ' + $(this).attr('id') + '</label>');
});

Bind an event handler to the click event for the selectAllBtn button. If the value of the element nameInput is not an empty string, trigger the select event, which will select all of the text within this element.

$('input#selectAllBtn').click(function () {
 if ($('input#nameInput').val() != '') {
  $('input#nameInput').select();
 }
});
Top

The .submit() method.

Submitting a form causes the submit event to be sent to the <form> element. The .submit() method is used to handle or trigger this event. Input elements with a type attribute equal to submit or image, and button elements with a type attribute equal to submit, are all capable of submitting forms. Alternatively, the submit event can be triggered from within another event handler.

The method has the following syntax:

  1. $( selector ).submit()
  2. $( selector ).submit( function( eventObject ) )
  3. $( selector ).submit( eventData, function( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event. The eventData parameter is an optional map of key/value pairs, and the data is passed to the event handler when the handler is bound to the event.

Three elements involved in the submit event have been extracted from a Web page. The form element mainForm, has its action attribute pointing to the url of another Web page. An event handler has been bound to the submit event for mainForm. Clicking the submitBtn element will trigger the event handler. If the content of the element nameInput is not an empty string, return true from the function, otherwise display an alert and return false. Returning true from the function will submit the form and the action attribute's url will be followed, directing the user to the Web page contact-us.htm. Returning false from the function prevents the form from being submitted.

<form id="mainForm" action="contact-us.htm" method="get">
Name:<input id="nameInput" type="text" />
Submit Form:<input id="submitBtn" type="submit" value="Submit" />
</form>

$('#mainForm').submit(function () {
 if ($('input#nameInput').val() != '') {
  return true;
 } else {
  alert('Please enter your name');
  return false;
 }
});
Top

The .toggle() method.

The .toggle() method is used to bind event handlers to the click event for the selected element. Each of these handlers will be triggered alternately on successive clicks of the element.

The syntax is: $( selector ).toggle( function( eventObject ), function( eventObject ), additional functions( eventObject ) )

The eventObject parameter is optional, and contains properties that give information about the event.

The .toggle() method is used to bind four event handlers to the click event for the toggleBtn element. The first click of the button changes each paragraph's background color to red. The second click changes the background color to green. The third click changes the background color to orange, and the fourth click removes the background color from the paragraph elements. Successive clicks of the button will repeat the cycle.

$('input#toggleBtn').toggle(function () {
 $('p').css('background-color', 'red');
},
function () {
 $('p').css('background-color', 'green');
},
function () {
 $('p').css('background-color', 'orange');
},
function () {
 $('p').css('background-color', '');
});
Top

The .trigger() method.

The .trigger() method is used to manually execute event handlers that have been bound to an event.

The method has the following syntax:

  1. $( selector ).trigger( eventType , additionalParameters ) )
  2. $( selector ).trigger( event )

The eventType parameter is the event name, passed into the method as a string value. The additionalParameters parameter can be used to pass additional data to an event handler. The event parameter is a jQuery.Event object, created using the jQuery.Event constructor. The constructor accepts an event type, and optionally an object, as its parameters.

Two variables are declared, and all paragraphs have their font size set to 16px. An event handler is bound to the click event for the fontSizeBtn element. If the fontSize variable is less than 25, the setTimeout() method is used to call the timer() function after a one second delay. If the variable is greater than 24, the clearTimeout() method is used to cancel the setTimeout() method and the fontSizeBtn element is disabled. The timer() function increases the fontSize variable by one. The function then selects all paragraph elements and sets their font size equal to the fontSize variable. Finally the .trigger() method is used to manually execute the click event handler attached to the fontSizeBtn. The cycle will repeat until the fontSize variable is greater than 24.

var t, fontSize=16;
$('p').css('font-size', '16px');

$('input#fontSizeBtn').click(function () {
 if (fontSize <= 24) {
  t = setTimeout('timer()', 1000);
 } else {
  clearTimeout(t);
  $(this).attr('disabled', 'true');
 }
});

function timer() {
 fontSize++;
 $('p').css('font-size', fontSize + 'px');
 $('input#fontSizeBtn').trigger('click');
}

An event handler, responsible for displaying an alert, is bound to click event for the eventBtn. A new jQuery.Event object is created, and the click event is passed as the first parameter to the constructor. The second parameter is an object literal, which has the property name Pizza and the value Pepperoni. This will become one of the event object's properties. The click event handler attched to the evntBtn is then triggered manually, passing the jQuery.Event object as the parameter to the .trigger() method. The value Pepperoni is then retrieved from the newly created property of the event object, and displayed in the alert.

$('input#eventBtn').click(function (event) {
 alert('The pizza topping is: ' + event.Pizza);
});

var e = jQuery.Event('click', { Pizza: 'Pepperoni' });
$('input#eventBtn').trigger(e);
Top

The .triggerHandler() method.

The .triggerHandler() method executes all event handlers bound to an event, but only for the first matched element. The event's default behaviour, however, does not take place. Event bubbling does not work with this method, and therefore event delegation cannot be used. The .triggerHandler() method does not return the jQuery object, unlike most methods, but instead returns the last executed event handler's returned value. The chaining of other methods, therefore, is not possible.

The syntax is: $( selector ).triggerHandler( eventType , additionalParameters ) )

The eventType parameter is the event name, passed into the method as a string value. The additionalParameters parameter can be used to pass additional data to an event handler.

An event handler is bound to the click event for testAnchor. The handler is passed the default event object as the first parameter, and two additional parameters. Clicking testAnchor displays an alert and causes the browser to navigate to the href attribute's url. The handler's color and weight parameters are undefined, and therefore the styles are not applied to the paragraphs.

Next, an event handler has been bound to the click event for the testBtn element. Clicking the button executes the click event handler for testAnchor, passing the two additional parameters to the handler. The alert message will be displayed, and all paragraphs will have their font color changed to red and font weight changed to bold. However, because the event has been triggered by the .triggerHandler() method, the default action of the anchor tag will no longer occur, and the browser will not navigate to the href attribute's url.

$('a#testAnchor').click(function (event, color, weight) {
 alert('Bye for now');
 if (color != undefined && weight != undefined) {
  $('p').css({ 'color': color, 'font-weight': weight }); 
 }
});

$('input#testBtn').click(function () {
 $('a#testAnchor').triggerHandler('click', ['red', 'bold']);
});
Top

Demo

     
     
     

The red box is 250px by 250px. The box has a target at its centre with the coordinates 125px by 125px relative to the box. The object of the game is to place the mouse pointer exactly over the target. A message is displayed when the target is hit.

To download the code for the demo click the Download Code link, or to see the code used with an explanation click the Show Code link.

Download Code Show Code