Reputation:
I can't understand this.
When I want to remove class B
from a div
and add class D
into it,
It works.
But class D
's function can't be triggered.
$('.B').click(function() {
$('.A').animate({
"left": "+=10%"
},{
duration:1000,
complete: function(){
$("#C").addClass("D").removeClass("B");
}
});
});
$(".D").click(function() {
$(".A").animate({
"top":"+=40%"
},{
duration:2000,
complete:function(){
$("#C").addClass("B").removeClass("D");
}
});
});
I've tried putting class D
's function into class B
's function like this:
$('.B').click(function() {
$('.A').animate({
"left": "+=10%"
},{
duration:1000,
complete: function(){
$("#C").addClass("D").removeClass("B");
$(".D").click(function() {
$(".A").animate({
"top":"+=40%"
},{
duration:2000,
complete:function(){
$("#C").addClass("B").removeClass("D");
}
});
});
}
});
});
and both functions work for the first time and after that they behavior in a bizarre way.
I would appreciate if someone can explain to me why and provide me with a solution.
Upvotes: 1
Views: 200
Reputation: 268344
When you use $.click
, you bind only to the elements that match the select at that time. If you want to match all future elements as well, use $.on
instead:
$("body").on("click", ".D", function(){
/* Class D Stuff */
});
This will react whether the clicked element had class="D"
to begin with, or if it acquired it later on through something like $(this).addClass("D")
.
The "body"
part ideally should be a container much closer to your clicked elements. For instance, if you had the following:
<body>
<div id="container">
<a href="#" class="B">Foo</a>
<a href="#" class="D">Bar</a>
</div>
</body>
You should use #container
instead of body
in the jQuery function.
Upvotes: 4