Reputation: 725
I am having problem with addClass()
and removeClass()
function in jquery. When i use the function it was replace the classes. but it was not calling the addded class functions. here is my query
HTML Code :
<div class="animation1 popbutton">Click Me</div>
Jquery :
$(".animation1").click(function(){
// my first function
});
$(".animation2").click(function(){
// my second function
});
and my add and remove class functions are,
$.ajax({
url : 'file.php',
data : postdata,
type : 'post',
success : function (saveresponseText)
{
$(".animation1").removeClass("animation1").addClass("animation2").html("Clicked");
}
});
if click the animation1
it will call the ajax function and it will replace the classname as animation2
and it has some separate function. how can do this? Someone suggest a solution please.
Thanks in Advance,
Upvotes: 0
Views: 1516
Reputation: 92
Try to add the event handler through document:
$(document).on('click','.animation2',function(){
// my second function
});
Upvotes: 2
Reputation: 2412
problem is that your ajax is not returning success check the console logs. actually problem was not with addClass and removeClass. see the example below.
in this example when you click on text click me it will call ajax request and ajax will result error so that code written in error is excecuted
$(document).ready(function() {
$(".animation1").click(function() {
// my first function
clk()
});
$(".animation2").click(function() {
// my second function
});
function clk() {
$.ajax({
url: 'file.php',
type: 'post',
success: function(saveresponseText) {},
error: function(status) { $(".animation1").removeClass("animation1").addClass("animation2").html("Clicked");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animation1 popbutton">Click Me</div>
Upvotes: 1
Reputation: 463
When you write
$(".animation1").click(function(){
// my first function
});
jQuery find the element with this class and adds a clickhandler to it. The function is not bound to the css-class.
I would suggest you either add a clickhandler in your ajax response, or have 2 buttons which you can hide / and show
Upvotes: 3