live() & delegate() functions of jQuery

live() & delegate() are two unique functions of jQuery. These two function look & act much like bind() function of jQuery. However they have a very different purpose.

We know that bind() function is used to binds Event Handlers to the elements matching the selector & already present in the DOM.

Lets say we have a button in the DOM with following markup.

<button id="btnSubmit" value="Submit" type="button">Click Me</button>

To attach Click Event Handler to the button, we use bind() function of JQuery as shown in the following snippet.

$('#btnSubmit').bind('click', function() {
  alert('User clicked on "Click Me"');
});

bind() function is pretty good if the element for which it is used is already present in the DOM. But, if the elements are added to the DOM on the go & we want that all the elements should have a Event Handler attached with them, then I won’t consider bind() function as the best option to attach Event Handlers. If we use bind() function in such scenario, then whenever a new element is added to the DOM, after each insertion we will have to call bind() function to attach a Event Handler to the newly added element. So to avoid this JQuery’s live() or delegate() functions can be used.

live() & delegate() functions provide similar event delegation functionality. They may sometimes seem as interchangable functions but at low level they are not. live() has several serious disadvantages & is suggested to be used. 

[Event Delegation Functionality: Event delegation works by binding to an element in the page, waiting for a DOM event to bubble to this element.]

HOW LIVE & DELEGATE WORKS:

Following is the code snippet of two jQuery functions live() & delegate() performing the same operation.

$('#container').delegate('button','click', function() {...});
$('#container button').live('click', function() {...});

The main difference between the two functions is, live() binds to the document & delegate() binds to the element on which its called on.

live() method provides a means to attach delegated event handlers to the document element of a page. So every time the event is triggered, it bubbles up in the tree to the document. This may be very time-consuming for large documents.

delegate() method instead provides a means to attach delegated event handlers to some parent element. So whenever the event is triggered, it bubbles up to the parent on which the method is called instead of document element.

So delegate() is a better option in terms of performance as compared to live().

Regex.test() function of javascript returns alternate results

Recently faced one strange issue. Regex.test() function of javascript was returning alternate results. I thought I made some mistake in writing the logic. But later when I debugged, I found that javascript function itself was behaving strangely. I googled it and found a new thing which I wasn’t knowing. So posting here for reference. Thanks to stack overflow 🙂

This is the RegExp which I was using [ /^([\+](?:\d{1,3})[-]\d{10})$/gi ]. Its a Global RegExp (contains g).

In JavaScript, Global RegExp have state which is used for finding multiple matches. We call either exec, test etc. methods to find match. First time execution of one of these methods give first match. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string.

There are two ways to change this behaviour (if you are dealing with single match):
(1) You can write regex.lastIndex= 0 to reset the state of the RegExp.
(2) Remove (g) from your RegExp.

[Reference: http://stackoverflow.com/questions/2630418/javascript-regex-returning-true-then-false-then-true-etc]

jQuery doesn’t fire onChange event on hidden fields by default

Changes in value of hidden input elements don’t automatically fire the .change() event. So, whenever you set the value of any hidden input element & want the change to be tracked, you explicitly have to tell jQuery to trigger change event on that hidden input element.

function changeStatus(statusValue) {
$('#status').val(statusValue).trigger('change');
}

…. and then …

$('#status').change(function(){
... Perform some function on change of value ...
})

jQuery unable to get/set value of hidden input

ISSUE:

I had the following hidden input in some part of my page –

<input id="selectedOption" type="hidden" value="">

This hidden input was added to hold the ‘city name’, which was going to be populated in hidden input on some button click event.
For populating the value I wrote the following jQuery script:

$('#btnBloreCity').click(function(){
   // alert($('#btnBloreCity').attr('value'));
   $('#selectedOption').val($('#btnBloreCity').attr('value'));
});

The code seemed to be fine & was also executing without any error. But still value was not getting populated to “selectedOption” hidden input.
I re-verified the id of hidden input with the one used in the jQuery selector. But found it matching.

REASON:

After an hour of investigation, I found that one more hidden input field with same id was present before this hidden input. That’s the reason why on button click the value was not being populated to the hidden input.

jQuery Id Selector’s Behaviour:

When we use Id selector of jQuery $(‘#Id’) for finding element with specified Id & If two elements with same id are present in the DOM, then the selector returns you the first one.

Explaination:

(1) Add following two hidden inputs in your page inside body.

<input id="selectedOption" type="hidden" value="Mumbai">
<input id="selectedOption" type="hidden" value="Bangalore">

(2) Add following script within head tag of your page.

<script type="text/javascript">
   $(document).ready(function(){
      alert('Selected City: '+$('#selectedOption').val());
   });
</script>

(3) View Page in browser.

So when the page is loaded, an alert pops up saying ‘Selected City: Mumbai’

Hope you got the basic point…
Page should not have elements with duplicate IDs