When I first click on a box it enlarges and when I click it again it shrinks back to its original size. This applies for all the boxes. But when I click on a box that has gone through these two events it does not grow again. I want all my boxes to always be able to grow and shrink back to their original sizes, not just once. Have a look at this fiddle
$(".item").on("click", function() {
$(this).addClass("grow");
$(".item").not(this).each(function() {
$(this).addClass("collapse");
})
$(this).on("click", function() {
$(this).removeClass("grow");
$(".item").not(this).each(function() {
$(this).removeClass("collapse");
})
})
})
Does anyone have a solution to this issue?
CodePudding user response:
Why not checking for .grow
class first? ↓
DEMO fiddle
$(".item").on("click", function() {
if ($(this).hasClass("grow")) {
$(this).removeClass("grow");
$(".item").not(this).each(function() {
$(this).removeClass("collapse");
});
} else {
$(this).addClass("grow");
$(".item").not(this).each(function() {
$(this).addClass("collapse");
});
}
})
CodePudding user response:
You don't need to write so long code. You can do this easily by using toggleClass() method. You even don't need collapse class to take box back to its normal position.
You can write your code as:
$(".item").on("click", function(){
$(this).toggleClass("grow");
});
Done. This small code can do your work.