If I click on a button, the color of the first div changes to black from white and the color of the second div changes to white from black, if I click on that button the vice-versa happens.
Asked
Active
Viewed 526 times
1
-
1What's the question? – Bikee Mar 23 '16 at 05:40
-
2Need to share your html and the js you have tried – Arun P Johny Mar 23 '16 at 05:40
-
Please, always show your basic HTML, CSS and JS code you attempted and explain what went wrong. – Roko C. Buljan Mar 23 '16 at 06:03
3 Answers
1
Using jQuery's .toggleClass()
http://api.jquery.com/toggleclass/
$("button").on("click", function(){
$("#a, #b").toggleClass("black");
});
div{width:200px; height:50px; background: #ccc;}
.black{background:#000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK ME</button>
<div id="a"></div>
<div id="b" class="black"></div>
Using bitwise XOR ^
to remember the button state:
https://stackoverflow.com/a/22061240/383904
$("button").on("click", function(){
var io = this.io ^= 1;
$("#a").css({background: io ? "#ccc" : "#000"});
$("#b").css({background: io ? "#000" : "#ccc"});
});
div{width:200px; height:50px; background:#000;}
#b{background:#ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK ME</button>
<div id="a"></div>
<div id="b"></div>
Using JS's Array.prototype.reverse()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
var colors = ["#000","#ccc"];
$("button").on("click", function(){
$("#a").css({background: colors.reverse()[0] });
$("#b").css({background: colors[1] });
});
div{width:200px; height:50px; background:#000;}
#b{background:#ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>CLICK ME</button>
<div id="a"></div>
<div id="b"></div>
Here's an additional reading if you want to use functions: https://stackoverflow.com/a/21520499/383904

Community
- 1
- 1

Roko C. Buljan
- 196,159
- 39
- 305
- 313
1
You can use toggleClass()
to acheive this.
Working Demo
$(document).ready(function(){
$("input").click(function(){
$('div').toggleClass('black , white')
});
});
.square{
width:100px;
height:100px;
border:1px solid red;
}
.black{
background-color:black;
}
.white{
background-color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square black"></div>
<div class="square white"></div>
<input type="button" value="Change">

Rino Raj
- 6,264
- 2
- 27
- 42
0
function toggleClass() {
$(".main div").toggleClass("black , white");
}
.main {
background-color: lightblue;
height: 50px;
width: 50px;
}
.black {
color: #000;
}
.white {
color: #fff;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div class="main">
<div class="black">first</div>
<div class="white">second</div>
</div>
<button onclick="toggleClass();">Toggle</button>

Drone
- 1,114
- 1
- 12
- 31