Bind Method-
.bind( eventType [, eventData ], handler ) ver-1.0
.bind( eventType [, eventData ] [, preventBubble ] ) ver-1.4.3
.bind( events ) ver-1.4
The .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object.
Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().
If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind( "click.name", handler ), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others.
A basic usage of .bind() is:
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
This code will cause the element with an ID of foo to respond to the click event. When a user clicks inside this element thereafter, the alert will be shown.
Multiple Events -
Multiple event types can be bound at once by including each one separated by a space:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <div> and remove the class when the mouse leaves.
As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing an object of event type/handler pairs:
$( "#foo" ).bind({
click: function() {
// Do something on click
},
mouseenter: function() {
// Do something on mouseenter
}
});
Event Handlers -
The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:
$( "#foo" ).bind( "click", function() {
alert( $( this ).text() );
});
The Event object -
The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.
Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.
Using the event object in a handler looks like this:
$( document ).ready(function() {
$( "#foo" ).bind( "click", function( event ) {
alert( "The mouse cursor is at (" +
event.pageX + ", " + event.pageY +
")" );
});
});
Passing Event Data -
The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:
var message = "Spoon!";
$( "#foo" ).bind( "click", function() {
alert( message );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", function() {
alert( message );
});
Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData:
var message = "Spoon!";
$( "#foo" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});
Examples:
Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bind demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click or double click here.</p>
<span></span>
<script>
$( "p" ).bind( "click", function( event ) {
var str = "( " + event.pageX + ", " + event.pageY + " )";
$( "span" ).text( "Click happened! " + str );
});
$( "p" ).bind( "dblclick", function() {
$( "span" ).text( "Double-click happened in " + this.nodeName );
});
$( "p" ).bind( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "over" );
});
</script>
</body>
</html>
Demo:
To display each paragraph's text in an alert box whenever it is clicked:
$( "p" ).bind( "click", function() {
alert( $( this ).text() );
});
You can pass some extra data before the event handler:
function handler( event ) {
alert( event.data.foo );
}
$( "p" ).bind( "click", {
foo: "bar"
}, handler );
Cancel a default action and prevent it from bubbling up by returning false:
$( "form" ).bind( "submit", function() {
return false;
})
Cancel only the default action by using the .preventDefault() method.
$( "form" ).bind( "submit", function( event ) {
event.preventDefault();
});
Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.
$( "form" ).bind( "submit", function( event ) {
event.stopPropagation();
});
HTML :
<ul id="members" data-role="listview" data-filter="true">
<!-- ... more list items ... -->
<li>
<a href="detail.html?id=10">
<h3>John Resig</h3>
<p><strong>jQuery Core Lead</strong></p>
<p>Boston, United States</p>
</a>
</li>
<!-- ... more list items ... -->
</ul>
$( "#members li a" ).bind( "click", function( e ) {} );
$( "#members li a" ).click( function( e ) {} );
The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.
Pros-
This methods works across various browser implementations.
It is pretty easy and quick to wire-up event handlers.
The shorthand methods (.click(), .hover(), etc...) make it even easier to wire-up event handlers.
For a simple ID selector, using .bind() not only wires-up quickly, but also when the event fires the event handler is invoked almost immediately.
Cons-
The method attaches the same event handler to every matched element in the selection.
It doesn't work for elements added dynamically that matches the same selector.
There are performance concerns when dealing with a large selection.
The attachment is done upfront which can have performance issues on page load.
Delegate Method-
.delegate( selector, eventType, handler ) ver- 1.4.2
.delegate( selector, eventType, eventData, handler ) ver- 1.4.2
.delegate( selector, events ) ver- 1.4.3
jQuery .delegate() method behaves in a similar way to the .live() method. But, instead of attaching the selector or event information to the document, you can choose where it is anchored. That is you can control on which node the events will be added. This can also respond to the dynamic element events.
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
For example, the following .delegate() code:
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
is equivalent to the following code written using .on():
$( "table" ).on( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});
Examples:
Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
</script>
</body>
</html>
Demo:
To display each paragraph's text in an alert box whenever it is clicked:
$( "body" ).delegate( "p", "click", function() {
alert( $( this ).text() );
});
To cancel a default action and prevent it from bubbling up, return false:
$( "body" ).delegate( "a", "click", function() {
return false;
});
To cancel only the default action by using the preventDefault method.
$( "body" ).delegate( "a", "click", function( event ) {
event.preventDefault();
});
Can bind custom events too.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
</script>
</body>
</html>
Live Method-
.live( events, handler ) ver - 1.3
.live( events [, data ], handler ) ver - 1.4
.live( events ) ver - 1.4.3
The .live method attaches the event handler to the root level document along with the associated selector and event information. By registering this information on the document it allows one event handler to be used for all events that have bubbled.Live method is deprecated from Jquery 1.7.
Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector
Examples:
Cancel a default action and prevent it from bubbling up by returning false.
$( "a" ).live( "click", function() {
return false;
});
Cancel only the default action by using the preventDefault method.
$( "a" ).live( "click", function( event ) {
event.preventDefault();
});
Bind custom events with .live().
$( "p" ).live( "myCustomEvent", function( event, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
Use an object to bind multiple live event handlers. Note that .live() calls the click, mouseover, and mouseout event handlers for all paragraphs--even new ones.
$( "p" ).live({
click: function() {
$( this ).after( "<p>Another paragraph!</p>" );
},
mouseover: function() {
$( this ).addClass( "over" );
},
mouseout: function() {
$( this ).removeClass( "over" );
}
});
Pros-
There is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method.
The upgrade path from .bind() to .live() is very small. All you have to do is replace "bind" to "live".
Elements dynamically added to the DOM that match the selector magically work because the real information was registered on the document.
You can wire-up event handlers before the document ready event helping you utilize possibly unused time.
Cons-
This method is deprecated as of jQuery 1.7 and you should start phasing out its use in your code.
Chaining is not properly supported using this method.
The selection that is made is basically thrown away since it is only used to register the event handler on the document.
Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document.
Since all selector/event information is attached to the document once an event does occur jQuery has match through its large metadata store using the matchesSelector method to determine which event handler to invoke, if any.
Your events always delegate all the way up to the document. This can affect performance if your DOM is deep.
On Method-
.on( events [, selector ] [, data ], handler ) ver- 1.7
.on( events [, selector ] [, data ] ) ver- 1.7
You can consider jQuery .on() method as being ‘overloaded’ with different signatures. This method attach the event handler function for one or more events to the selected elements. jQuery .on() function was included in jQuery 1.7 so, for early versions it will not work.
function greet( event ) {
alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {
name: "Karl"
}, greet );
$( "button" ).on( "click", {
name: "Addy"
}, greet );
var $test = $( "#test" );
function handler1() {
console.log( "handler1" );
$test.off( "click", handler2 );
}
function handler2() {
console.log( "handler2" );
}
$test.on( "click", handler1 );
$test.on( "click", handler2 );
Examples:
Display a paragraph's text in an alert when it is clicked:
$( "p" ).on( "click", function() {
alert( $( this ).text() );
});
Pass data to the event handler, which is specified here by name:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Cancel a form submit action and prevent the event from bubbling up by returning false:
$( "form" ).on( "submit", false );
Cancel only the default action by using .preventDefault().
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
});
Stop submit events from bubbling without preventing form submit, using .stopPropagation().
$( "form" ).on( "submit", function( event ) {
event.stopPropagation();
});
Pass data to the event handler using the second argument to .trigger()
$( "div" ).on( "click", function( event, person ) {
alert( "Hello, " + person.name );
});
$( "div" ).trigger( "click", { name: "Jim" } );
Use the the second argument of .trigger() to pass an array of data to the event handler
$( "div" ).on( "click", function( event, salutation, name ) {
alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );
Attach and trigger custom (non-browser) events.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "p" ).on( "myCustomEvent", function( event, myName ) {
$( this ).text( myName + ", hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function () {
$( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>
</body>
</html>
Demo:
Attach multiple event handlers simultaneously using a plain object.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
.test {
color: #000;
padding: .5em;
border: 1px solid #444;
}
.active {
color: #900;
}
.inside {
background-color: aqua;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="test">test div</div>
<script>
$( "div.test" ).on({
click: function() {
$( this ).toggleClass( "active" );
}, mouseenter: function() {
$( this ).addClass( "inside" );
}, mouseleave: function() {
$( this ).removeClass( "inside" );
}
});
</script>
</body>
</html>
Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
var count = 0;
$( "body" ).on( "click", "p", function() {
$( this ).after( "<p>Another paragraph! " + (++count) + "</p>" );
});
</script>
</body>
</html>
Display each paragraph's text in an alert box whenever it is clicked:
$( "body" ).on( "click", "p", function() {
alert( $( this ).text() );
});
Cancel a link's default action using the .preventDefault() method:
$( "body" ).on( "click", "a", function( event ) {
event.preventDefault();
});
Attach multiple events—one on mouseenter and one on mouseleave to the same element:
$( "#cart" ).on( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "active" );
});
/* The jQuery .bind(), .live(), and .delegate() methods are just one
line pass throughs to the new jQuery 1.7 .on() method */
// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
.bind( eventType [, eventData ], handler ) ver-1.0
.bind( eventType [, eventData ] [, preventBubble ] ) ver-1.4.3
.bind( events ) ver-1.4
The .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object.
Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().
If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind( "click.name", handler ), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others.
A basic usage of .bind() is:
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
This code will cause the element with an ID of foo to respond to the click event. When a user clicks inside this element thereafter, the alert will be shown.
Multiple Events -
Multiple event types can be bound at once by including each one separated by a space:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <div> and remove the class when the mouse leaves.
As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing an object of event type/handler pairs:
$( "#foo" ).bind({
click: function() {
// Do something on click
},
mouseenter: function() {
// Do something on mouseenter
}
});
Event Handlers -
The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:
$( "#foo" ).bind( "click", function() {
alert( $( this ).text() );
});
The Event object -
The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.
Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.
Using the event object in a handler looks like this:
$( document ).ready(function() {
$( "#foo" ).bind( "click", function( event ) {
alert( "The mouse cursor is at (" +
event.pageX + ", " + event.pageY +
")" );
});
});
Passing Event Data -
The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:
var message = "Spoon!";
$( "#foo" ).bind( "click", function() {
alert( message );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", function() {
alert( message );
});
Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData:
var message = "Spoon!";
$( "#foo" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", {
msg: message
}, function( event ) {
alert( event.data.msg );
});
Examples:
Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>bind demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click or double click here.</p>
<span></span>
<script>
$( "p" ).bind( "click", function( event ) {
var str = "( " + event.pageX + ", " + event.pageY + " )";
$( "span" ).text( "Click happened! " + str );
});
$( "p" ).bind( "dblclick", function() {
$( "span" ).text( "Double-click happened in " + this.nodeName );
});
$( "p" ).bind( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "over" );
});
</script>
</body>
</html>
Demo:
To display each paragraph's text in an alert box whenever it is clicked:
$( "p" ).bind( "click", function() {
alert( $( this ).text() );
});
You can pass some extra data before the event handler:
function handler( event ) {
alert( event.data.foo );
}
$( "p" ).bind( "click", {
foo: "bar"
}, handler );
Cancel a default action and prevent it from bubbling up by returning false:
$( "form" ).bind( "submit", function() {
return false;
})
Cancel only the default action by using the .preventDefault() method.
$( "form" ).bind( "submit", function( event ) {
event.preventDefault();
});
Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.
$( "form" ).bind( "submit", function( event ) {
event.stopPropagation();
});
HTML :
<ul id="members" data-role="listview" data-filter="true">
<!-- ... more list items ... -->
<li>
<a href="detail.html?id=10">
<h3>John Resig</h3>
<p><strong>jQuery Core Lead</strong></p>
<p>Boston, United States</p>
</a>
</li>
<!-- ... more list items ... -->
</ul>
$( "#members li a" ).bind( "click", function( e ) {} );
$( "#members li a" ).click( function( e ) {} );
The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.
Pros-
This methods works across various browser implementations.
It is pretty easy and quick to wire-up event handlers.
The shorthand methods (.click(), .hover(), etc...) make it even easier to wire-up event handlers.
For a simple ID selector, using .bind() not only wires-up quickly, but also when the event fires the event handler is invoked almost immediately.
Cons-
The method attaches the same event handler to every matched element in the selection.
It doesn't work for elements added dynamically that matches the same selector.
There are performance concerns when dealing with a large selection.
The attachment is done upfront which can have performance issues on page load.
Delegate Method-
.delegate( selector, eventType, handler ) ver- 1.4.2
.delegate( selector, eventType, eventData, handler ) ver- 1.4.2
.delegate( selector, events ) ver- 1.4.3
jQuery .delegate() method behaves in a similar way to the .live() method. But, instead of attaching the selector or event information to the document, you can choose where it is anchored. That is you can control on which node the events will be added. This can also respond to the dynamic element events.
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
For example, the following .delegate() code:
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
is equivalent to the following code written using .on():
$( "table" ).on( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});
Examples:
Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
</script>
</body>
</html>
Demo:
To display each paragraph's text in an alert box whenever it is clicked:
$( "body" ).delegate( "p", "click", function() {
alert( $( this ).text() );
});
To cancel a default action and prevent it from bubbling up, return false:
$( "body" ).delegate( "a", "click", function() {
return false;
});
To cancel only the default action by using the preventDefault method.
$( "body" ).delegate( "a", "click", function( event ) {
event.preventDefault();
});
Can bind custom events too.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delegate demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
</script>
</body>
</html>
Live Method-
.live( events, handler ) ver - 1.3
.live( events [, data ], handler ) ver - 1.4
.live( events ) ver - 1.4.3
The .live method attaches the event handler to the root level document along with the associated selector and event information. By registering this information on the document it allows one event handler to be used for all events that have bubbled.Live method is deprecated from Jquery 1.7.
Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector
Examples:
Cancel a default action and prevent it from bubbling up by returning false.
$( "a" ).live( "click", function() {
return false;
});
Cancel only the default action by using the preventDefault method.
$( "a" ).live( "click", function( event ) {
event.preventDefault();
});
Bind custom events with .live().
$( "p" ).live( "myCustomEvent", function( event, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
Use an object to bind multiple live event handlers. Note that .live() calls the click, mouseover, and mouseout event handlers for all paragraphs--even new ones.
$( "p" ).live({
click: function() {
$( this ).after( "<p>Another paragraph!</p>" );
},
mouseover: function() {
$( this ).addClass( "over" );
},
mouseout: function() {
$( this ).removeClass( "over" );
}
});
Pros-
There is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method.
The upgrade path from .bind() to .live() is very small. All you have to do is replace "bind" to "live".
Elements dynamically added to the DOM that match the selector magically work because the real information was registered on the document.
You can wire-up event handlers before the document ready event helping you utilize possibly unused time.
Cons-
This method is deprecated as of jQuery 1.7 and you should start phasing out its use in your code.
Chaining is not properly supported using this method.
The selection that is made is basically thrown away since it is only used to register the event handler on the document.
Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document.
Since all selector/event information is attached to the document once an event does occur jQuery has match through its large metadata store using the matchesSelector method to determine which event handler to invoke, if any.
Your events always delegate all the way up to the document. This can affect performance if your DOM is deep.
On Method-
.on( events [, selector ] [, data ], handler ) ver- 1.7
.on( events [, selector ] [, data ] ) ver- 1.7
You can consider jQuery .on() method as being ‘overloaded’ with different signatures. This method attach the event handler function for one or more events to the selected elements. jQuery .on() function was included in jQuery 1.7 so, for early versions it will not work.
function greet( event ) {
alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {
name: "Karl"
}, greet );
$( "button" ).on( "click", {
name: "Addy"
}, greet );
var $test = $( "#test" );
function handler1() {
console.log( "handler1" );
$test.off( "click", handler2 );
}
function handler2() {
console.log( "handler2" );
}
$test.on( "click", handler1 );
$test.on( "click", handler2 );
Examples:
Display a paragraph's text in an alert when it is clicked:
$( "p" ).on( "click", function() {
alert( $( this ).text() );
});
Pass data to the event handler, which is specified here by name:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Cancel a form submit action and prevent the event from bubbling up by returning false:
$( "form" ).on( "submit", false );
Cancel only the default action by using .preventDefault().
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
});
Stop submit events from bubbling without preventing form submit, using .stopPropagation().
$( "form" ).on( "submit", function( event ) {
event.stopPropagation();
});
Pass data to the event handler using the second argument to .trigger()
$( "div" ).on( "click", function( event, person ) {
alert( "Hello, " + person.name );
});
$( "div" ).trigger( "click", { name: "Jim" } );
Use the the second argument of .trigger() to pass an array of data to the event handler
$( "div" ).on( "click", function( event, salutation, name ) {
alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );
Attach and trigger custom (non-browser) events.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "p" ).on( "myCustomEvent", function( event, myName ) {
$( this ).text( myName + ", hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function () {
$( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>
</body>
</html>
Demo:
Attach multiple event handlers simultaneously using a plain object.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
.test {
color: #000;
padding: .5em;
border: 1px solid #444;
}
.active {
color: #900;
}
.inside {
background-color: aqua;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="test">test div</div>
<script>
$( "div.test" ).on({
click: function() {
$( this ).toggleClass( "active" );
}, mouseenter: function() {
$( this ).addClass( "inside" );
}, mouseleave: function() {
$( this ).removeClass( "inside" );
}
});
</script>
</body>
</html>
Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
var count = 0;
$( "body" ).on( "click", "p", function() {
$( this ).after( "<p>Another paragraph! " + (++count) + "</p>" );
});
</script>
</body>
</html>
Display each paragraph's text in an alert box whenever it is clicked:
$( "body" ).on( "click", "p", function() {
alert( $( this ).text() );
});
Cancel a link's default action using the .preventDefault() method:
$( "body" ).on( "click", "a", function( event ) {
event.preventDefault();
});
Attach multiple events—one on mouseenter and one on mouseleave to the same element:
$( "#cart" ).on( "mouseenter mouseleave", function( event ) {
$( this ).toggleClass( "active" );
});
/* The jQuery .bind(), .live(), and .delegate() methods are just one
line pass throughs to the new jQuery 1.7 .on() method */
// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
No comments:
Post a Comment