Handling Events in jQuery – Few Advanced Notes and Faqs

Background:

We have already discussed about handling client events in jQuery (see earlier post). Obviously there are more things about jQuery events like binding client events to DOM element which are created dynamically, Cancelling the action of an event conditionally etc. Let’s have a look at few advanced topics on jQuery events.

Adding event handler to future elements:

In my earlier post we already know about the bind() and unbind() methods provided by jQuery which is used to attach and detach event handlers to various elements on the page. Instead of bind() we can also use the click()/dblclick() methods to add different event handlers. We declare these things in the ready() event because we need that element to be loaded before we attach any event handler to that element.

Since we can create DOM element dynamically, can we use this technique to attach event to the element. The answer is no, because when the dynamically created element is not yet present in the DOM when the ready event is executed. We can still manually attach the handler to the newly created element but there is a smarter way to do that using the live() method that jQuery provides.

Let’s consider the following example

<divid="myTestArea">
<ahref="#"onclick="AddElement();">Add Element</a>
<divclass="box">Existing Element</div>
</div>

<scripttype="text/javascript">
$(function()
    {
        $(".box").bind("mouseover", function()
        {
           $(this).css("background-color", "red");
        }).bind("mouseout", function()
        {
           $(this).css("background-color", "white");
        });
    });

    functionAddElement()
    {
       vardiv = $("<div></div>").addClass("box").text("Added Element");
       $("#myTestArea").append(div);
    }
</script>

Here, we have created an event handler for both “mouseover” and “mouseout” events to all elements using class selector “box”. Though we are dynamically adding the elements which have the same class “box”, things does not work out for those div which are created dynamically. In order to make this work we have to replace the bind method with the live() method and we are done. With the live() method jQuery will observe any changes to the DOM and will attach the event handler with those element that are newly created.

Similarly like the unbind() method we have the die() method that will work for detaching the event handler dynamically.

N.B: line() and die() methods are available on jQuery version 1.7 onwards.

Stop event method to perform: preventDefault or return false?

During the execution of a jQuery event we may need to stop the execution midway. One very popular way to do that is to write “return false” also we are all aware of the in-built jQuery event preventDefault(). So let’s have a closure look at these two options and different pros and cons about using these two.

When we use the preventDefault() method it actually stops executing the current function, but does not stops the event to be bubble up. So the subsequent events will be triggered. In order to stop the event to bubble up we have to use the stopPropagation() method.

On the other hand return false, it actually does both. i.e calling return false is equivalent to calling both preventDefault() and stopPropagation().

So as we can see both these options are useful, but that depends on the need we have as a programmer. Consider a jQuery click() event of an anchor tag <a> and we have to stop the navigation. So we can write the preventDefault() at the beginning of the method so that user is not navigated away. We cannot use the return false in this case, because we have to use the return false once the execution of the function is done, and if there is an unhandled exception in between the return false statement will not be executed.

Attaching and detaching event handler: New ways to do that

As we have seen in earlier post. We can use the bind() and unbind() methods to attach and detach event handler respectively. Though these two methods are still available for backward compatibility, version1.7 onwards jQuery provides on() and off() functions to attach and detach event handlers.

So the new way of doing this will be
:

$('#mybutton').click(function() { returnfalse; }); // Adds another click event
$('#mybutton').off('click');
$('#mybutton').on('click.samplenamespace', function() { /* Code here */ });
$('#mybutton').off('click.samplenamespace');

This way we have more control about attaching and detaching event handlers in case we have multiple handlers attached to an element.

Playing with DOM attributes: jQuery method attr() and prop()

While we have used jQuery selectors and Manipulate DOM in the earlier post, I have discussed about the attr() method to read and modify HTML attribute for DOM elements. If we look deep into the DOM tree, there are attributes and there are some properties of the DOM element. Apparently they looks similar but there are differences.

From version 1.6 onwards, jQuery provides prop() method, which allows us to read and modify the properties of the DOM elemeny.The .prop() method provides a way to explicitly retrieve property values, and the .attr() retrieves attributes.

Attributes:

Attributes holds additional information about a HTML element and defined as name=”value”.
If we look at the below example:

<input id="myText"type="text"value="myValue">

here, "type","value", "id" are attributes of the input elements.

Property:

Propertiesare representation of an attribute in the HTML DOM tree object. When the HTML code is parsed by the browser,corresponding DOM node is created as an object and all attributes are attached with that object as properties.
In case of theexample,once browser renders the textbox, other properties like align, alt, autofocus, checked so on are added.

attr() gives us the value of element as defined in the html during the design.The advantage of using prop() iswe can get theoriginal value of an element also the current state values of element. So it is recommended to use the prop() methodto modify attributes via jquery.


JavaScript window.onload vs jQuery ready function

The main difference between JavaScript onload event and jQuery ready function is that former not only waits for DOM to be created but also waits until all external resources are fully loaded including heavy images, audios and videos. If loading images and media content takes lot of time that user can experience significant delay on execution of code defined in window.onload event. On the other hand jQuery ready() function only wait for DOM tree, and does not wait for images or external resource loading, means faster execution. Another advantage of using jQuery $(document).ready() is that you can use it multiple times in your page, and browser will execute them in the order they appear in HTML page, as opposed to onload technique, which can only be used for a single function. Given this benefits, it's always better to use jQuery ready() function than JavaScript window.onload event. See answer article for more deep discussion.
  

detach() vs remove()

Though both detach() and remove() method is used to remove a DOM element, Main difference between them is that detach() keep track of the last element detached, so that it can be reattached, while remove() method does keep reference of last removed method. This is one of the many jQuery interview question from DOM manipulation. You can also take a look on appendTo() for adding element into DOM.

Comments

Popular posts from this blog

Ways to select DOM element(s) - a guide to jQuery Selectors

Let's traverse through DOM Tree - Few advanced notes on jQuery Selectors