Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text.
I have tried using onclick stop propagation to prevent the div from hiding when clicking on the input box. However, applying the same logic to 'click for event 2' prevents the div from hiding and also stops the other event from occurring.
To sum up:
1. Clicking the first 'event 2' text should only change the background color between blue and red without hiding the lightgreen div.
2. Clicking the 2nd 'event 2' text should display an alert box but not hide the pink parent div
How can I achieve these goals? Following a recent question, I attempted adding 'preventPropagation' to different elements and made a few other efforts, all in vain.
I am fairly new to JS, so any explanation would be greatly appreciated. Thank you.
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>