There are two divs with class of .egg. The user is supposed to click on the div they want to change the background color of and then click the color for the div's new background. Two steps total. I've written a jQuery function to capture the id of the div chosen for the background change and then the id for the color to change to background. Works great, except that when the new div is selected, to change the background color, the previously selected div id is still stored in the variable called clickedId.
To try to fix this problem, I have set clickedId = ''; after the background has been changed for the selected div. However when a new div is selected, it doesn't work anymore. The console says Cannot read property 'style' of null. It looks like the first part of the code, $(".egg").click(function() {... isn't be executed for new div selections.
Does anyone have any suggestions or advice for this? Thanks in advance!
jQuery Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Select the div to change the background color
$(".egg").click(function() {
var clickedId = $(this).attr("id");
//Updating the background color for selected div
$(".color").click(function() {
var clickedColor = $(this).attr("id");
if(clickedColor == 'red'){
document.getElementById(clickedId).style.backgroundColor = "red";
clickedId = '';
return;
}else if(clickedColor == 'blue'){
document.getElementById(clickedId).style.backgroundColor = "blue";
clickedId = '';
return;
}else if (clickedColor == 'yellow') {
document.getElementById(clickedId).style.backgroundColor = "yellow";
clickedId = '';
return;
}else{
document.getElementById(clickedId).style.backgroundColor = "white";
clickedId = '';
return;
}
});
});
});
</script>
HTML Code:
<body>
<div id="egg-main">
<div id="left-egg"></div>
<div id="center-egg1" class="egg" onclick="semi_left()"></div>
<div id="center-egg2" class="egg" onclick="semi_right()"></div>
<div id="right-egg"></div>
<div id="bottom">
<div id="red" class="color"></div>
<div id="blue" class="color"></div>
<div id="yellow" class="color"></div>
<div id="white" class="color"></div>
</div>
</div>
<script src="demo.js"></script>
</body>