jquery click event on anchor

72,747

!THIS is tested and working.

You forgot to put your code inside the document ready function

$(function() {
//your code
});
Share:
72,747
djeetee
Author by

djeetee

Updated on August 05, 2022

Comments

  • djeetee
    djeetee almost 2 years

    Here's the snippet of html i have:

    <div id="tag-cloud-widget">  
        <div class="content">  
            <a href="#" rel="1" class="cloud-element" data-tag-id="10" style="font-size: 12px; color: rgb(205, 236, 222); ">T1</a>  
            <a href="#" rel="1" class="cloud-element" data-tag-id="1" style="font-size: 12px; color: rgb(205, 236, 222); ">T2</a>  
            <a href="#" rel="1" class="cloud-element" data-tag-id="3" style="font-size: 12px; color: rgb(205, 236, 222); ">T3</a>  
        </div>
    </div>
    

    I'd like to set up a click handler to respond to the user's click on the anchor tags. Here's the test code:

    $("#tag-cloud-widget .content a").click(function(e) {
        alert('clicked');  
        return false;  
    });  
    

    The click handler above does not get fired and neither does this:

    $("#tag-cloud-widget .content .cloud-element").click(function(e) {  
        alert('clicked');  
        return false;  
    });  
    

    However,

    $("#tag-cloud-widget .content").click(function(e) { ... });  
    

    and

    $("#tag-cloud-widget").click(function(e) { ... });  
    

    do get fired!

    What am I not seeing???

  • Karl Nicoll
    Karl Nicoll over 13 years
    JQuery should apply the event handler to all elements that match the selector. In this case, the click event handler should be applied to all three anchors.
  • Kushal
    Kushal over 13 years
    The below two code snippets given in question are working as per what @djeetee says, so that's not the case.
  • Kushal
    Kushal over 13 years
    So how would you differentiate that which anchor was clicked, if all the three anchors share common click method?
  • johnlemon
    johnlemon over 13 years
    @Kush you are wrong, the script is placed before the dom content, so it's not applied correctly. I tested with document ready and it works fine.
  • Karl Nicoll
    Karl Nicoll over 13 years
    Normally, you'd use the this keyword to get the current element, or if you're using JQuery, you can use the $(this) to get the JQuery object for the element. So to use your code, you could create the same function for all the elements' click events, and do this: alert(this.id + " clicked!);. That would show "anca Clicked" for the first one, and "ancb clicked" for the second one, and so on.
  • Kushal
    Kushal over 13 years
    @Karl Nicoll: Okay so in order to perform particular action this.id can be used to differentiate anchors through conditional chain. Thanks. :-)