Bhoot
Bhoot

Reputation: 400

strange behaviour of jquery 'click' event

I had an anchor tag

<li><a href="#" class="institution">Click me</a></li>
<li><a href="#" class="department">Click me</a></li>
<li><a href="#" class="branch">Click me</a></li>

i wanted to execute some code by clicking on the anchor tag.so i used

$('a').click(function(){
    //do something..
});

but it did not work out. So I used

$('a').on('click',function(){
    //do something..
});

also i used

$('a').bind('click',function(){
    //do something..
});

but they did not work either. what worked for me was

$('a').live('click',function(){
    //do something..
});

why is this so..when all of them are supposed to show same behaviour.

Upvotes: 0

Views: 167

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70159

.click and .bind don't have event delegation. You're executing them before the elements are loaded into the DOM. Either move your .click to below the anchors or add it inside a DOM ready event:

$(document).ready(function() {
    $('a').click(function(){
        //do something..
    });
});

OR

$(function() {
    $('a').click(function(){
        //do something..
    });
});

Both of the above have the same result, use whichever you find more readable/maintainable.

.live works right now as it uses event delegation, which is, per a layman's view, similar to

$(document).on('click', 'a', function(){
    //do something..
});

Note that .live is deprecated in jQuery 1.7+ so you should prefer the .on method for event delegation. Also note that .on only has the event delegation effect when bound to a parent element passing a descendants selector parameter.

Here's a Fiddle with $(document).ready().

edit: As per OP's comment, since you're adding anchor tags dynamically, you have 2 options: event delegation (recommended) or re-binding the events every time you add new content.

In jQuery 1.7+, you should use .on() for event delegation:

$('#AnchorsDivID').on('click', 'a', function(){
    //do something..
});

Here's a full featured live demo with .on event delegation and Ajax:
JSFiddle

In jQuery <=1.6.4, you will have to use .delegate() or .live(). Which one provides better usability and performance for each version is shown at the .live() jQuery API page.

For jQuery >=1.4.3 <1.7:

$('#AnchorsDivID').delegate('a', 'click', function(){
    //do something..
});

Upvotes: 7

tftd
tftd

Reputation: 17032

This code works absolutely fine with your html:

$(document).ready(function(){
    $('a').on('click', function(e){
        console.log('some action.');
    });
});

P.S. this code will run on all links!

Upvotes: 0

Related Questions