Monkeybrain
Monkeybrain

Reputation: 840

jQuery click function is not attaching click event to anchor

HTML

Inside <div id='foo-bar-baz'> I have a series of image links with unique ids as below

<a href=''><img id='12341234' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>
<a href=''><img id='56785678' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>

Javascript / JQuery

The above div is created by a $.get() to a webservice which returns a chunk of HTML in variable response. On success, the $.get() calls the below function:

var thumbnailsDiv = function (response) 
    {
        var json = $.parseJSON(response);
        $('#foo-bar-baz').html(json.html);
        alert("Setting click functions on thumbnails");
        $('.foo-bar-thumbnail-image').unbind().click(function () {
            alert("I am thumbnail " + $(this).id);
        }, false);
    };

As you can see above, I'm trying to bind a click function to each of the image links. However this is not working (with or without the unbind()).

After the above code has run, if I inspect the image links in the Dev Tools, I can see that there are two click event attached already to the thumbnails. Neither of these is my function above. The paths for both of them are from other applications libraries embedded on the page: one is labelled 'jQuery' and the other is labelled 'Bubbling' and 'DOM2'. I'm guessing that it is these attached events that mean I can't add my event above, but I don't know enough about jQuery or javascript to know if this is true (I am a server-side developer normally, I don't know front-end stuff at all.)

Any suggestions as to how I get an on-click event working for these elements would be much appreciated, so that I can replace the demo code above with the code I need to run.

Upvotes: 2

Views: 2801

Answers (2)

Michael Coker
Michael Coker

Reputation: 53674

You should be using $(document).on('click','.foo-bar-thumbnail-image',function() ... instead of $.click(function()... since the event handler is on elements that were rendered on the page via JS. That's a "delegated" event handler - you can read more about that here https://learn.jquery.com/events/event-delegation/

Upvotes: 3

Dan Nagle
Dan Nagle

Reputation: 5425

You just need to bind the click event to the parent element which already exists on the page.

$('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){
  // what you want to happen when click 
  // occurs on elements that match '.foo-bar-thumbnail-image'
  // within '#foo-bar-baz'
  alert("I am thumbnail " + $(this).id);
});

Upvotes: 3

Related Questions