Reputation: 8481
Good day to all,
I want to toggle classes as soon as I click to one of the images. Once I click I want to add a class to that div
with a name expand
to give it a little transition effect. So here's my problem. First click, OK. Second click, the class expand
won't go off. Here are some of my files.
Any help would be much appreciated. Thanks.
index.html
<div class="box1">
<div class="content">
<img src="img/some.png" />
</div>
</div>
some.js
$(function () {
$("img").on("click", function() {
var box = $(this).first().parents().eq(1).attr("class");
$("."+box).toggleClass("expand");
});
});
some.css
.box1 {
width: 50%;
height: 50%;
float: left;
position: relative;
font-size: 2em;
}
div {
-webkit-transition-property: width, height;
-webkit-transition-duration: 2s;
}
div.expand {
width: 100%;
height: 100%;
}
Upvotes: 2
Views: 920
Reputation: 337560
Your code does not work on successive clicks because you are taking the entire class
attribute and then looking for the element named $('.box1 expand')
, which does not exist. Instead, use toggleClass
on the element itself, instead of building the class selector:
$("img").on("click", function() {
$(this).first().parents().eq(1).toggleClass("expand");
});
Or alternatively, you can clean the code slightly by using closest()
:
$("img").on("click", function() {
$(this).closest('box1').toggleClass("expand");
});
Upvotes: 4