Background click through select input
If you click on the select input the backrgound click event is triggered through the select, input and wrapper tags. In Chrome on Windows 10 the select <options> triggers the event.
by jwerre
HTML
<div id="background"></div>
<div id="wrapper">
<p>
If you click on the select input the backrgound click event is triggered through the select, input and wrapper tags. In Chrome on Windows 10 the clicking on the select <options> triggers the event rather than the select input itself.
</p>
<form>
<select id="select" >
<option value="">Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
</div>
CSS
#background {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: -1;
box-sizing: border-box;
width: 100%;
height: 100vh;
background: cyan;
padding: 50px;
font-family: sans-serif;
}
#wrapper {
margin: 0 auto;
padding: 50px;
width: 80%;
background: lightgray;
}
form {
padding: 50px;
background: darkgray;
text-align: center;
}
select {
width: 300px;
height: 50px;
border: none;
border-radius: 3px;
padding: 10px;
}
JavaScript
const bg = document.getElementById('background');
bg.addEventListener("click", bgClickHandler);
function getRandomColor () {
return `#${Math.floor(Math.random()*16777215).toString(16)}`;
}
function bgClickHandler (e) {
e.preventDefault();
if(e.target.id === 'background') {
console.log('Click event triggered on correct element');
} else {
console.log(`Click event triggered on the wrong element: ${e.target.tagName}`);
}
bg.style.backgroundColor = getRandomColor();
}