Reputation: 2191
After reading a couple of posts like this one, I'm trying to discover a way to be able to click on the parent div to hide itself, but not hide when clicking on either the search box or the 'click for event 2' text.
I've used the onclick stop propagation to prevent the div from hiding when clicking on the input box, but if I do the same for 'click for event 2', this prevents the div from hiding BUT also prevents the other event from happening.
To summarise:
1. Clicking the first 'event 2' text should just change the background colour between blue and red, and not hide the lightgreen div.
2. Clicking the 2nd 'event 2' text should show the alert box but then not hide the pink parent div
How can these be achieved? After a recent question, I've tried adding 'preventPropagation' etc to different elements and a few other attempts, but to no avail.
I'm relatively new to JS so any explanation would be very helpful. Thanks.
function doThis() {
var el = document.querySelector('#test1');
if (el.style.display === 'flex') {
el.style.display = 'none';
} else {
el.style.display = 'flex';
}
}
function andThis() {
var x = document.querySelector('.test2');
if (x.style.background === 'red') {
x.style.background = 'blue';
} else {
x.style.background = 'red';
}
}
function doThisTwo() {
var re = document.querySelector('#test3');
if (re.style.display === 'flex') {
re.style.display = 'none';
} else {
re.style.display = 'flex';
}
}
function andThisTwo() {
alert('hi');
}
#test1 {
background: lightgreen;
display: flex;
}
.test2 {
background: red;
}
#test3 {background: pink}
<button onclick='doThis()'>click me</button>
<div id='test1' onclick='doThis()'>
text <input onclick='event.stopPropagation()' type="text">
<span class='test2' onclick='andThis()'>click for event 2</span>
</div>
<br><br>
<button onclick='doThisTwo()'>click me too</button>
<div id='test3' onclick='doThisTwo()'>
text <input onclick='event.stopPropagation()' type="text">
<span class='test4' onclick='andThisTwo()'>click for event 2</span>
</div>
Upvotes: 0
Views: 1414
Reputation: 46
If you put event as an argument for the hiding function - say, doThis(event) - you can evaluate event.target (what the user actually clicked) in the function.
So if the class of the thing you clicked === the event2 button class - don't run the function.
Upvotes: 1