How To Use The jQuery delegate() And on() Methods

jquery delegateLooking for an explanation of the jQuery delegate() method?  We’ll talk about it here, and tell you how to use it, as well as the on() method, which replaces delegate() in more recent versions of jQuery.

There are plenty of opportunities for skilled web programmers and designers, and knowledge of both JavaScript and jQuery is an essential element of present-day web development.  You can find first-rate online classes covering all aspects of web programming.  Take a look today  —  you’ll like what you see!

jQuery In A Very Small Nutshell

Since we’re going to be talking about jQuery, we’ll start by telling you what it is.  It’s a library of JavaScript code that add a variety of features and functions to basic JavaScript  —  mostly things that go on in the user’s browser (rather than on the web server).  It’s free, and it’s open-source; you can download jQuery (it’s a single JavaScript file) and use a local copy, or link to one of the publicly-available online instances of jQuery (including those maintained by Amazon, Google, Microsoft, and the jQuery Foundation itself).

Using jQuery

To link to an instance of the jQuery library, you include a line like the following in the <head> section of the HTML page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

The basic syntax for using jQuery looks like this:

$(select_an_element).do_something_to_it(arguments, functions, and other stuff)

In other words, you use a jQuery selector to determine what HTML elements, tags, etc, are going to be affected (by generic tag name, such as “div”, or by ID), then you use a jQuery (plus its arguments and functions) to capture an event (such as a button click), and/or perform an action (change formatting, assign values, run one or more functions).

In our examples, we’ll place most of the jQuery code within the ready() method:

$(document).ready(function(){...});

It’s a rather cautious way of making sure that the page is fully loaded before the code executes.  You may not need it for your code, but if you do, it will save you a lot of trouble.

jQuery delegate() And on()

What are delegate() and on() all about?  We’ll start with delegate(), since it came first. It’s one of those programming-language commands that’s usually described in very abstract terms:  it “attaches event handlers” to the selected elements, along with the function to be run when the event occurs.

Selecting elements and running functions are easy  —  that’s what jQuery does all of the time, anyway.  But what are event handlers?  They are methods which register a user action (such as click(), mouseover(), or keypress()), and can be used to trigger an event: the user clicks on something, and the program does something in response.  So delegate() basically says, “For these page elements, when the user does this, we do this action in response.”

But Wait, There’s More!

“But,” you may be saying, “don’t most jQuery methods do that?  What else does it do?”  And that is exactly the point  —  it delegates the whole process to the specified elements which are subordinate to (i.e., “children of”) the selected element.  Take a look at this line of code:

$("#this_div").delegate("p","click",function(){$(this).text("You clicked here.");

First, we select a specific <div> element by ID (“#this_div”). Then within the delegate() method’s arguments, we specify all <p> elements (“p”) within that <div>, along with the event, a user click (“click”), and the action, a function that replaces any <p> element that the user clicks with the specified text.

The action uses the JavaScript “this” keyword, which, when used in the manner shown, refers to whatever is on the receiving end of the method. And since we’re talking about the delegate() method, it actually does delegate; in this case, it delegates the whole process to the <p> elements which are subordinate to the specified <div>.  So what it’s really saying is more like this:   “For any of these items within these page elements, when the user does this, we do this action in response.”

Turn on()

Now for the bad news:  don’t use delegate().

It’s a little more complicated than that, of course.  You should use delegate() if you need to be compatible with versions of jQuery prior to 1.7, but if you aren’t worried about backward compatibility (and typically with jQuery, you wouldn’t be), you should use the on() method (introduced with jQuery version 1.7) instead, for a variety of reasons which we won’t go into here.

The good news is that in most cases, on() and delegate() are almost identical in use.  Here’s our delegate() example with on() substituted for delegate():

$("#this_div").on("click","p",function(){$(this).text("You clicked here.");

The only difference (besides changing “delegate” to “on”) is that with on(), the event argument (“click”) comes first, and the selector argument (“p”) comes second, and with the delegate() method, the order is reversed.

Tell Me A Story

OK.  Here’s a working example of what you can do with event handler delegation (using on() since we want to follow current standards):

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#get_it").click(function(){
  var the_name = $("#i_am").val();
     $("#the_story").on("click","span",function(){
    $(this).html("<font color='#FF0000'>" + the_name + "</font>");
    }); 
   });
 });
</script>
</head>
<body>
<p>What's your name?&nbsp;&nbsp; <input type="text" id="i_am" >
&nbsp;&nbsp; <button id="get_it">OK</button><p>
<p>Which character in this story would you like to be?</p>
<h2>The Three Little Aardvarks</h2>
<div style="width:400px" id="the_story"><p><font face="Georgia">
Once upon a time, there were three little aardvarks, <span>Edwina</span>, 
<span>Eldred</span>, and <span>Albermarle</span>, who lived in an abandoned 
flying-saucer base on the far side of the moon...</font></p></div>
</html>

It’s pretty simple:  Enter your name, click on the OK button, then click on one of the name of one of the characters in the story.  Your name will replace the name that you clicked (in red, so it stands out).  You can copy the code, paste it to a text file, save the file with the .HTM extension, and open it in your browser to test it.

Getting It on()

In the HTML, we asked the user to input a name, and saved it as “the_name”, then we created a <div> with the ID “the_story”, and we tagged the three names in the text with <span>.  In the jQuery code, we select the <div>, and we use the on() method to say, “When the user clicks on any <span> element in the <div>, change the content of the <span> to the indicated HTML code.”

JavaScript, jQuery, and web development – knowledge of these and other subjects can open a lot of doors.  And there are plenty of online courses that can get you started in web programming, in jQuery, and in JavaScript.  Why not check a few out?