Adjit
Adjit

Reputation: 10305

Calling on a newly create class

Was just messing around, and I know why this doesn't work, but I don't see any other way to do it...

Simple function :

$(".click").on("click", function() {
    alert("first click");
    $(this).removeClass("click");
    $(this).addClass("next");
});
$(".next").on("click", function(){
    alert("second click");
});

however, I always get the "first click" alert. So I know this is because when the page is created the next class is not there...

What would be a good way around this?

Here is my test fiddle :

http://jsfiddle.net/tUp9R/1/

Upvotes: 1

Views: 38

Answers (3)

effy
effy

Reputation: 430

add this after $(this).addClass('next').click(); and move the .next click function at the begining so the browser knows what to do when the function is called.

here's the complete code.

`$(".next").on("click", function(){
alert("second click");
});
$(".click").on("click", function() {
alert("first click");
$(this).removeClass("click");
$(this).addClass("next").click();
});`

Upvotes: -1

bottens
bottens

Reputation: 3902

You can use event delegation: http://jsfiddle.net/tUp9R/4/

jQuery documentation: https://learn.jquery.com/events/event-delegation/

Javascript:

$(".test").on("click", ".click", function() {
    alert("first click");
    $(this).removeClass("click");
    $(this).addClass("next");
});

$(".test").on("click", ".next", function() {
    alert("second click");
});

HTML:

<div class="test">
    <button class="click">Click Me</button>
</div>

You could also simplify it a bit by using event data like so: http://jsfiddle.net/tUp9R/7/

$(".click").on("click", {first: true}, function(e) {
    if (e.data.first) {
        alert("first!")
        e.data.first = false
    } else {
        alert("not first :)")
    }
})

Upvotes: 3

Felix
Felix

Reputation: 38112

You can apply event delegation syntax using .on() here:

$(document).on("click", '.click',function(){
    alert("first click");
    $(this).removeClass("click");
    $(this).addClass("next");
});

$(document).on("click", '.next',function(){
    alert("second click");
});

Updated Fiddle

Upvotes: 2

Related Questions