William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery examples summary 5

Continue the summary.

1. delegate( selector, events )
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

$("table").delegate("td", "hover", function(){
 $("td", this).live("hover", function(){
$("body").delegate("p", "click", function(){
 $(this).after("<p>Another paragraph!</p>");
$("body").delegate("a", "click", function(event){
jQuery('#mydiv').delegate('#mydiv > p', 'click', function() { 

2. event.target
The DOM element that initiated the event.

$("body").click(function(event) {
  $("#log").html("clicked: " + event.target.nodeName);
function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {

3. live( eventType, handler )
.live() is my favorite. It is very powerful. However, it may occur performance issue, so use it when have to.
Attach a handler to the event for all elements which match the current selector, now and in the future.

 click: function(){// do something on click},
 mouseover: function() {// do something on mouseover }
$("p").live("myCustomEvent", function(e, myName, myValue) {
 $(this).text("Hi there!");
 $("span").stop().css("opacity", 1)
   .text("myName = " + myName)
 $("button").click(function () {

$("p").live("click", function(){
 $(this).after("<p>Another paragraph!</p>");
 "mouseover": function() {
 "mouseout": function() {

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.

To cancel only the default action by using the preventDefault method.

$("a").live("click", function(event){

4.trigger( eventType, extraParameters )
Execute all handlers and behaviours attached to the matched elements for the given event type. Using .trigger(‘click’) will not trigger the native click event. To simulate a default click, you can bind a click handler like so:

$('#someLink').bind('click', function() {
  window.location.href = this.href;
  return false;
$('input.mycheckbox').click(function() {
  if (this.checked) {

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: