jQuery: The Write Less, Do More JavaScript Library

Release:jQuery 1.2/Events

From jQuery JavaScript Library

Jump to: navigation, search

« Back to the full jQuery 1.2 Release Notes.

Namespaced Events

This is a piece of functionality that's especially useful for plugin authors. You can now provide a private name for the event handlers that you bind, allowing you to remove them again later (without having to maintain a private cache of all the handlers that you're overseeing).

Attach and remove custom handlers to see how they behave. Note that the normal, default, click handler remains untouched.

$("#exec").click(function(){
  $("#results").prepend("<li>Normal Handler</li>");
});
$("#add").click(function(){
  $("#exec").bind("click.custom", function(){
    $("#results").prepend("<li>Custom Event Handler</li>");
  });
});
$("#remove").click(function(){
  $("#exec").unbind("click.custom");
});

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("#exec").click(function(){
  $("#results").prepend("<li>Normal Handler</li>");
});
$("#add").click(function(){
  $("#exec").bind("click.custom", function(){
    $("#results").prepend("<li>Custom Event Handler</li>");
  });
});
$("#remove").click(function(){
  $("#exec").unbind("click.custom");
});
  });
  </script>
  
</head>
<body>
  <button id="exec">Click Me</button>
<button id="add">Add Custom</button>
<button id="remove">Remove All Custom</button>
<ul id="results"></ul>
</body>
</html>

.triggerHandler()

A new method that can be used in addition to the original .trigger(). This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.

If you called .triggerHandler() on a focus event - the browsers default focus action would not be triggered, only the event handlers bound to the focus event.

$("#old").click(function(){
  $("input").trigger("focus");
});
$("#new").click(function(){
  $("input").triggerHandler("focus");
});
$("input").focus(function(){
  $("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("#old").click(function(){
  $("input").trigger("focus");
});
$("#new").click(function(){
  $("input").triggerHandler("focus");
});
$("input").focus(function(){
  $("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});
  });
  </script>
  
</head>
<body>
  <button id="old">.trigger("focus")</button>
<button id="new">.triggerHandler("focus")</button><br/><br/>
<input type="text" value="To Be Focused"/>
</body>
</html>