Is there a way to make jQuery listen for clicks only at specific times? It seems that when I add event listeners, like $("#box").click(function(){
, they are executing before the code above them finishes running.
Let's say I have two boxes that should respond to clicks in sequence - with the second box only becoming clickable after the first one has been clicked. Once clicked, both boxes should stop listening for further clicks. For example, box1
should turn red first, followed by box2
.
I've tried searching for solutions without much success. I also experimented with adding if
statements, but then the second box never triggers. Any assistance on this matter would be highly appreciated.
pass = 0;
function change() {
console.log("enter change");
$("#box").click(function() {
$(this).css("background-color", "red");
pass = 1;
})
if (pass > 0) {
$("#box2").click(function() {
$(this).css("background-color", "red");
})
}
}
div {
height: 100px;
width: 100px;
background-color: black;
display: inline-block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div id="box"></div>
<div id="box2"></div>
<button onclick="change()"> change</button>