Jeffz
Jeffz

Reputation: 2105

jquery after() method

I have a simple function:

$(".slider").click(function () {

    $(this).after('<span class="slider">click me again</span>');

 });

//before first click   
<span class="slider">first click</span>

//after first click
<span class="slider">first click</span>
<span class="slider">click me again</span>

When I click on "click me again", function does not fire.

I tried, live and on and a few other ways, but to no avail.

What am I doing wrong?

Upvotes: 1

Views: 150

Answers (3)

Purag
Purag

Reputation: 17061

You say you used on(), so I'm led to believe you were using it incorrectly.

The syntax required for on() to work on dynamic elements is like such:

$(document).on("click", ".slider", function(){
    // click event fired
});

Notice that we're targeting the document and delegating the click event to all children with the class slider.

It is recommended to use as close a parent as possible for on(), because when you use document, events bubble up to the document level, which can lower performance and slow things down. So it's better to target the closest parent of the spans that exists when the page loads.

live() is also deprecated, so for versions of jQuery below 1.7, it is much more preferred and in fact recommended to use delegate().

More on on() here and more on delegate() here.

Upvotes: 0

Raffael
Raffael

Reputation: 1139

Using the live() method works fine, actually:

$(".slider").live('click',function () {
    $(this).after('<span class="slider">click me again</span>');
});

Make sure do embed this code in your $(document).ready() handler.

Upvotes: 0

Rob W
Rob W

Reputation: 349042

Use .live(), .delegate() or .on() (jQuery 1.7) to bind the event:

$(document).on("click", ".slider", function () {
    ...

.click( ... ) is short for .bind('click', ...), which only binds the event to the elements which exist at that time. Elements which are added later do not receive this event listener.

Upvotes: 4

Related Questions