I am given a task of making 7 nested div’s such that the clicked div should change its colour to white, while all the upper div’s of clicked div should change their colour to orange. While all the lower div’s should change their colour to green.
$(".div").click(function() {
$(this).css({
"background-color": "white"
});
$(this).parents().css({
"background-color": "orange"
});
$(this).children().css({
"background-color": "green"
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
<style>
div {
border: 2px solid black;
margin: 30px 20px;
}
</style>
</head>
<body>
<div id="main">
<div class="div" id="1">
<div class="div" id="2">
<div class="div" id="3">
<div class="div" id="4">
<div class="div" id="5">
<div class="div" id="6">
<div class="div" id="7">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
>Solution :
You’re quite close, actually! The reason for the boring and non-interactive output is due to how events are bubbled through elements. Here’s a great article on mdn about events, but the most important bit is around stopping the propagation.
The standard Event object has a function available on it called stopPropagation() which, when invoked on a handler’s event object, makes it so that first handler is run but the event doesn’t bubble any further up the chain, so no more handlers will be run.
So in your example, the original div might be clicked, but the other divs also receive the click and will run their code. Try adding a event.stopPropagation() and seeing how it changes.
P.S. You’ll need to get the event object in your click handler 🙂
P.P.S. I believe starting to use more console.log and sooner-rather-than-later familiarizing yourself with debugging tools will help you immensely. In this case adding a console.log statement in the click handler, for example, would have had you asking the question, "why does my click trigger on multiple elements?"