jQuery add remove class onclick to a div
19,179
Solution 1
Try using .toggleClass()
$(".content.firstArrow").toggleClass("rotate");
Solution 2
You can optimize the code and leave one handler only:
$(document).ready(function(){
$('#first, #second, #third, #forth').click(function(event) {
$(".content." + $(this).attr('id') + "Arrow").toggleClass("rotate");
});
});
Author by
user2271599
Updated on June 04, 2022Comments
-
user2271599 almost 2 years
I have created the code below, which successfully rotates an arrow, via the class rotate, on the first click.
But on the second click, i want the arrow to rotate back again. I have tried, using an else, and removing class on click. But this hasn't worked. Any suggestions, or help, would be great!
$(document).ready(function(){ $('#first').click(function(event) { $(".content.firstArrow").addClass("rotate"); }); $('#second').click(function(event) { $(".content.secondArrow").addClass("rotate"); }); $('#third').click(function(event) { $(".content.thirdArrow").addClass("rotate"); }); $('#forth').click(function(event) { $(".content.forthArrow").addClass("rotate"); }); });