Introduction to jQuery_2

Module 2.1.

Before Start

The following contents are the notes I took when learning jQuery on Edx.

Mainly for front-End Web developers, check here to get more details.


Three parts:

Module2 : Managing content, events and effects

Module2 includes six parts:

  • Event handlers
  • Modifying elements
  • Registering event handlers
  • Adding new elements
  • Animations
  • Removing, replacing and cloning

Let’s get to know something about the first three parts.

  • Event handlers

    Event object:

    Beyond just the object that raised the event, jQuery (and JavaScript) also pass an event object to the event handler.

    This object can be used to determine additional information, such as where the mouse was when the user performed the operation.


    // Write out the x/y coordinates of the mouse on click
    $('button').click(function(e) {
        $('#output').text(e.pageX + 'x' + e.pageY);
    • Click


      $('#target').click(function() { alert('hello, world!'); });
    • dbclick

      raised when the user double clicks on an element.


      $('#target').dbclick(function(){ alert('hello, world!'); });
    • Forms : blur, change, focus

      • blur

        raised when a form element loses what’s known as focus. often used for validation.


        $('#target').blur(function() {
            // retrieve the value using val
            var value = $('#target').val();
      • change

        raised whenever an element is to input, textarea and select elements only.


        $(function() {
          $('#parent').change(function() {
            var value = $('#parent').val();
            $('#child').append('<option>1 - ' + value + '</option>');
            $('#child').append('<option>2 - ' + value + '</option>');
      • focus

        the opposite of blur. raised when the user clicks, taps, or tabs into a particular control, typically because they want to change its value.


        <!-- sample HTML -->
            <label for="phone">Phone</label>
            <input type="text" id="phone" />
            <span id="phone-help"></span>
        // sample JavaScript
        $('#phone').focus(function() {
            // Control has focus. Display help
            $('#phone-help').text('Please enter your phone number as all digits');
        }).blur(function() {
            // Control lost focus. Clear help
    • Mouse movement

      • mouseenter, mouseleave

        mouseenter is raised whenever the user moves their mouse over an element.

        mouseleave is raised when the user moves their mouse away from an element.


        <!-- sample HTML -->
            <span id="target">Basic data</span>
            <span id="target-help"></span>
        // sample JavaScript
        $('#target').mouseenter(function() {
            $('#target-help').text('More data');
        }).mouseleave(function() {
      • hover

        equivalent to both the mouseenter and mouseleave events. The first parameter hover accepts is for mouseenter, or when the hover begins, and the second parameter is for mouseout.


        $('#target').hover(function() {
            // mouseenter
            $('#target-help').text('More data');
        }, function() {
            // mouseleave

  • Modifying elements

    • Replacing element HTML and text

      • val

        for read the value, like to say retrieve the value of an input control, you can use val()

        var value = $('#some-input-control').val();

        also, you can set the value. use val(new-value)

        Example: set a textbox to a blank value

        // Empty a textbox
      • html

        you have saw it in Module1.


        // write text out to the screen
        // this will be displayed as
        // <strong>value</strong>
        // the text value will not be bolded
      • text


        // write text out to the screen
        // this will be displayed as value
        // with the word bolded
    • Working with attribute and classes

      • attr

        To retrieve the value of an attribute, simply call attr(name).

        To change the value of an attribute, simply call attr(name, newValue).

      • addClass and removeClass

        You have known it in Module1. Besides, one nice thing about removeClass is it will not throw an error if the class doesn’t exist.

    • Working with styles

      • css

        To retrieve the value of a CSS property, call css(property).

        To set a property, call css(property, newValue)


        // Retrieve an item's color
        var color = $('#target').css('color');
        // Change an item's color to red
        $('#target').css('color', 'red');

        To set multiple properties, create a JavaScript object with the property/value pairs, and then pass the object into the css function.


        var style = {
            color: 'red',
            backgroundColor: yellow
  • Registering event handlers

    • Dynamic event handlers

      • on, off

        Both on and off share the same syntax:

        $('selector').on/off('events', 'selector (optional)', function)

        Here, events: A space separated list of the events you wish to register, such as 'click' or 'click mouseenter'

        BTW, Obviously if you need to dynamically choose the event, or if you need multiple events for the same event handler, using on is your only choice.

        In additon, on offers one more feature, known as delegation.

    • Delegation

      Registering an event handler using delegate, is similar to on, with one major difference: New elements will automatically have the event handler applied.

      The delegate syntax:

      $(selector).delegate(selector, events, eventHandler)


      <!-- sample HTML -->
      <div id="placeholder"></div>
      $(function() {
          // document.ready (on load)
          // register a click event handler with all button elements, except new button
          //$('button').click(function() { alert('hello'); });
          // new button will also be raised
          $(document).delegate('button', 'click', function() { alert('hello'); });
          // create a new button
          $('#placeholder').html('<button>New button</button>');

      With jQuery 1.7, delegate is superseded by on.

      One important thing to note is the order of parameters for on and delegate.

      With on, you list the events first and the selector second. With delegate, it’s selector followed by events.


      // Delegation (note the order of parameters)
      $(document).on('click', 'button', function() {alert('hello'); });
      // Semantically the same as above
      // (note the order of parameters)
      $(document).delegate('button', 'click', function() { alert('hello'); });
    • Single execution

      • one

        one shares a similar syntax with on, only there is no delegation option.

        The event only execute once.


        <!-- sample HTML -->
        <button id="single">This only works once</button>
        <div id="output"></div>
        $(function() {
            $('#single').one('click', function() {
                $('#output').text('You clicked on the button');
    • Triggering events

      Raise the event programatically, like to click on a button to refresh data.

      trigger and triggerHandler allow you to provide the name of the event as a parameter.

      trigger will execute for all elements in the collection,

      while triggerHandler only executes the handler for the first element.


      <!-- sample HTML -->
      <button type="button" id="first">First button</button>
      <button type="button" id="Second">Second button</button>
      <button type="button" id="trigger">trigger</button>
      <button type="button" id="trigger-handler">triggerHandler</button>
      $(function() {
          $('button').click(function() {
              // display the id of the button
          $('#trigger').click(function() {
              // Would alert every button's id
              // including the last two
          // Would alert "first"
          $('#trigger-handler').click(function() {
              // Would alert "first"

      This is the first three parts of Module2 all about. More details.