Sean H Jenkins
Sean H Jenkins

Reputation: 1780

JQuery .on() method not firing?

I am trying to use the JQuery on() method. Basically I am trying to write an alert box similar to the one on here. If you've ever tried to vote on your own comment or thread, you'll know what I'm talking about.

I have a JS function like below which simply returns my box with the message.

function alert_box(msg){
    return "<div class='alert-box'><p>" + msg + "<br /><i>( Click to Close )</i></p></div>";
}

I then call the alert-box like so

$(that).append( alert_box(data.err) );

The above works as expected but the problem is this function not triggering. The .alert-box gets added with the above code but doesn't get removed with the below.

$('.alert-box').on({
    click: function() {
        $('.alert-box').remove();
    }
});

I assume its something to do with the .alert-box class being added after the DOM. Anyone got any pointers on this?

Upvotes: 0

Views: 145

Answers (1)

jfriend00
jfriend00

Reputation: 707198

The form of .on() you were using does not handle dynamically added content. If you want to change it to handle dynamic content, then you can use this where you pass it a common parent object and then an argument for the selector to filter by:

The prototype for that form of .on() is this: .on( events-map [, selector] [, data] ). And your code would work like this:

$(document.body).on({
    click: function() {
        $('.alert-box').remove();
    }
}, '.alert-box');

In this new form, you're attaching an event handler to a parent object and then looking for clicks in any children that match the '.alert-box' selector. It's best to pick a parent object that is as close to where your clicks will be, but one that doesn't change. I used document.body here just because I know that exists and you haven't shown your other HTML for me to know what else could be used.

Upvotes: 5

Related Questions