My request is as follows: I have multiple boxes displayed on a webpage, each containing clickable divs and text. When a user clicks on a clickable div, an alert should appear confirming the click. Clicking on the text itself should not trigger any action. However, here's where it becomes more complex.
Upon clicking on a box, it should acquire the class open
. If a user clicks anywhere outside of a box or its children, the class open
should be removed. Clicking on a clickable div within the box should not affect the box's class.
If a user clicks on another box, the original box should retain the open
class while the new box also acquires this class. Clicking on the header, body, or anything else besides the boxes should remove the open
class. Remember that clicking on a clickable div should display an appropriate alert.
It seems like there are many event targeting scenarios involved here, so I'm curious if you have a good solution for this.
To demonstrate, please ensure that when a box has the open
class, its background turns green. Clicking on elements such as the header or body should revert the box back to its original steelblue color. If a user clicks on a clickable child div, the box's background should turn green and an alert should pop up.
Below is some sample code:
$(document).on("click", function(e) {
//is there somthing like:
// if `this` is not the box or children of box remove the
// class `open` from box. this way if they click on header or body I could remove
//the `open` class from box
if (e.target == this) {
$(".box").removeClass("open")
} else if ($(e.target).hasClass("box")) {
$(e.target).addClass("open")
}
if ($(e.target).hasClass("test1")) {
alert("test1")
}
if ($(e.target).hasClass("test2")) {
alert("test2 clicked")
}
if ($(".box").hasClass("open")) {
$(this).css("background", "green")
}
})
.box {
margin: 4em 5em;
background: steelblue;
width: 15em;
height: 8em;
padding: .1em;
}
.clicker {
width: 5em;
background: lightgreen;
padding: .2em;
cursor: pointer;
}
.header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 3em;
background: tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="header">header</div>
<div class="box">
<p>this is the box</p>
<p class="test1 clicker">Test click</p>
<p class="test2 clicker">Test click 2</p>
</div>
<div class="box">
<p>this is the box</p>
<p class="test1 clicker">Test click</p>
<p class="test clicker">Test click 2</p>
</div>