Connecting Events to Elements

Contact Us or call 1-877-932-8228
Connecting Events to Elements

Connecting Events to Elements

jQuery offers convenience methods for most common events, and these are the methods you will see used most often. These methods, including $.fn.click, $.fn.focus, $.fn.blur, $.fn.change, etc, are shorthand for jQuery's $.fn.on method. (Note that, in earlier versions of jQuery, the $.fn.bind method was used; it has been deprecated, as of jQuery version 1.7 in favor of $.fn.on.) The on method is useful for binding the few browser events for which jQuery does not have a convenience method, or binding the same handler function to multiple events, and is also used when you are working with custom events.

Within the event handler function, the this object will be the element that you bound the event handler to (unless you use $.proxy to change that).

Event Binding Using a Convenience Method

Code Sample:

jqy-events/Demos/convenience-event-binding.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
</head>
<body>
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<script>

// Using this as an ordinary HTML element object
$('p:odd').click(function() {
    console.log('click odd' + ": " + this.innerHTML);
});

// Using $(this) as a jQuery single-element collection
$('p:even').click(function() {
    console.log('click even' + " - " + $(this).html());
});
</script>
</body>
</html>

We establish two event handlers: one for odd rows, and the other for even rows. For odd rows, we use the this object, which will be the object that received the click (the paragraph element), as an ordinary JavaScript HTML element object, and access its innerHTML property.

For even rows, we wrap this into a jQuery collection object with $(this), and then use the html() method for the same purpose.

Attaching Event Handlers Using the $.fn.on Method

This method can be used to attach a handler for any type of event, including custom events that you would create yourself.

$('p').on('click', function() { console.log('click'); });

Attaching Events With Data

Each event-attaching convenience function has a second form that takes two parameters. In this form, the second parameter is the target, and the first parameter is a map of data that will be given to the handler through the event object.

Code Sample:

jqy-events/Demos/data-event-binding.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
</head>
<body>
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<script>
var counter = 0;

// Using this as an ordinary HTML element object
$('p:odd').click(
	{ type: 'odd' },
	function(e) {
		console.log('click ' + e.data["type"] + ": " + this.innerHTML);
	}
);

// Using $(this) as a jQuery single-element collection
$('p:even').click(
	{ type: 'even' },
	function(e) {
		console.log('click ' + e.data["type"] + " - " + $(this).html());
	}
);
</script>
</body>
</html>

We again establish two event handlers, but for each one have added a data object with a type property of either "odd" or "even". When the event occurs, we can retrieve that information through the data property of the event object passed to the handler.

The on method also has a form that accepts a data object, as the second parameter (between the event name and the handler function).

Connecting Events to Run Only Once

Sometimes you need a particular handler to run only once -- after that, you may want no handler to run, or you may want a different handler to run. jQuery provides the $.fn.one method for this purpose.

Switching Handlers Using the $.fn.one Method

Code Sample:

jqy-events/Demos/switching-handlers.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
</head>
<body>
<p>One</p>
<p>Two</p>
<p>Three</p>
<p>Four</p>
<script>
$('p').one(
	'click',
	function() {
		console.log('You just clicked this for the first time!');
		$(this).click(
			function() { console.log('You have clicked this before!'); }
		);
	}
);
</script>
</body>
</html>

The $.fn.one method is especially useful if you need to do some complicated setup the first time an element is clicked, but not subsequent times.

Code Sample:

jqy-events/Demos/lazy-load.html
---- C O D E   O M I T T E D ----
	</div>
	<div class="disclosure">
		<h3 class="control">Edit Content</h3>
		<div class="content"></div>
	</div>
	
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
<script>
$(document).ready(
	function() {
		$('.disclosure .control').each(function() {
			var $this = $(this);
			var $div = $this.next('div.content');
			$this.one('click',
				function(e) {
					$div.html("<p>Some</p><p>New</p><p>Content</p>");
					$div.slideDown();
					$this.click(
						function() {
							$div.slideToggle();
						}
					);
				}
			);
		});
	}
);
</script>
</body>
</html>

In this application, there is an in it ally empty, hidden, div beneath a trigger element. Clicking on the trigger will run a one-time event handler to:

  • load the div (which in real life would be done using Ajax)
  • show the div
  • set up ongoing event handling to toggle the open/close state of the div with each click on the trigger

Removing Events Handlers

To remove an event handler, you use the $.fn.off method and pass in the event type to remove. If you attached a named function to the event, then you can isolate the removal to that named function by passing it as the second argument.

Removing All Click Handlers on a Selection

$('p').off('click');

Removing a Particular Click Handler

var foo = function() { console.log('foo'); };
var bar = function() { console.log('bar'); };

$('p').on('click', foo).on('click', bar);
$('p').off('click', bar); // foo is still attached to the click event

Namespacing Events

For complex applications and for plugins you share with others, it can be useful to namespace your events so you don't unintentionally disconnect events that you didn't or couldn't know about.

$('p').bind('click.myNamespace', function() { /* ... */ });
$('p').off('click.myNamespace');
$('p').off('.myNamespace'); // unbind all events in the namespace

Using mouseenter/mouseleave Instead of mouseover/mouseout

While mouseenter and mouseleave are proprietary Internet Explorer events, their behavior is useful in all browsers. jQuery simulates mouseenter and mouseleave for the other browsers.

The main difference, and why mousenter/mouseleave are useful, is that the mouseover and mouseout events bubble, so that if you move the mouse the mouse into an element, and then into a child element, the mouseover event will fire twice. First, as expected, when we move onto the element. But, the event fired on the child element will also bubble up to the containing element. The behavior of mouseout can be even more problematic. So, mouseenter and mouseleave provide a convenient way to trap the behavior you normally want - the events on a child element do not bubble up to its parent.

Next