Reputation: 10305
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 :
Upvotes: 1
Views: 38
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
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
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");
});
Upvotes: 2