Reputation: 1046
I have 2 divs named yellowUp
with up arrows as background images.
As it is now, when I click on a yellowUp
div, only the clicked div changes class. How do I make both divs change class on click?
HTML
<div class="yellowUp"></div>
<div class="yellowUp"></div>
<div id="contentContainer"></div>
CSS
.yellowUp {
background-image: url(../images/arrow-up.png);
}
.clicked {
background-image: url(../images/arrow-down.png);
}
jQuery
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$(this).toggleClass("clicked");
return false;
});
Upvotes: 0
Views: 106
Reputation: 1046
Thanks Nic,
I went with this really simple option (to me at least):
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
$(".yellowUp").css("background-image", "url(images/arrow-up.png)");
} else {
$("#contentContainer").stop().animate({marginTop:"100px"}, 200);
$(".yellowUp").css("background-image", "url(images/arrow-down.png)");
}
$(this).toggleClass("clicked");
return false;
});
I just added a css background image change for each condition.
Upvotes: 0
Reputation: 6894
If you want both .yellowUp
divs to have the .clicked
class when 1 is clicked, then instead of doing $(this).toggleClass("clicked");
just select the class instead.
jQuery
$(".yellowUp").toggleClass("clicked");
$(".yellowUp").click( function(event){
event.preventDefault();
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$('.yellowUp').toggleClass("clicked");
return false;
});
.yellowUp {
color: blue;
}
.clicked {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="yellowUp">Hi</div>
<div class="yellowUp">Hi</div>
<div id="contentContainer">BLah</div>
Upvotes: 1
Reputation: 8670
it's because you only change the class of the clicked object. instead, use :
$(document).ready(function(){
$('.yellowUp').on('click', function(e){
e.preventDefault();
$('.yellowUp').each(function($key, $index) {
if ( $(this).hasClass("clicked") ) {
$("#contentContainer").stop().animate({marginTop:"0px"}, 200);
} else {
$("#contentContainer").stop().animate({marginTop:"-300px"}, 200);
}
$(this).toggleClass("clicked");
});
});
});
In the previous code we parse each element with the class yellowUp to toggle clicked.
hopes it helps !
Upvotes: 0