Nick
Nick

Reputation: 1277

Event not fired after trigger change

There's no better way to express my problem than to show you an example. http://jsfiddle.net/CA6aQ/

$(document).ready(function() {

    $('#foo').click(function(e) {
       e.preventDefault();
       $('#bar').addClass("herro");
    });

    $('.herro').click(function(e) {
       alert("Hello World!"); 
    });


});

Why doesn't this work?

Thanks.

EDIT: To clarify, when I add a class to an element. The click event for that class trigger doesn't fire.

Upvotes: 1

Views: 87

Answers (2)

Purag
Purag

Reputation: 17071

Since the class is added dynamically, you have to use the on() function (works with jQuery 1.7 and higher). For earlier versions use live().

Example.

$(document).ready(function() {
    $('#foo').click(function(e) {
       e.preventDefault();
       $('#bar').addClass("herro");
    });
    $(document).on('click', '.herro', function() {
       alert("Hello World!"); 
    });
});

Notice the difference in syntax. What we do is select the document, bind the click event to it, check if the click event was fired on the .herro element, and then fire the function. It works the same way as click except it will work with dynamic elements (in your case, the class you were selecting didn't exist at the page load).

Upvotes: 1

Vigrond
Vigrond

Reputation: 8198

on .click is set when there are no .herro classes. Use jQuery .on() to 'delegate' events.

example: http://jsfiddle.net/CA6aQ/2/

 $('body').on('click', '.herro', function(e) {
       alert("Hello World!"); 
    });

ref: http://api.jquery.com/on/

Also, please copy your code into Stackoverflow, as jsfiddle may not always be available, and this doesn't help anyone. Stackexchange is a community help site, try to contribute a little bit to its success : )

Upvotes: 0

Related Questions