Philip Dortmund Philip Dortmund - 6 months ago 51
CSS Question

Prevent event in over-positioned elements

I'm having some issues with this "workflow".

I have a div which contains an image being used as banner, it covers a good proportion of the screen, in this div there are also some inputs, they have attached the blur and keypress events, so whenever the user types on them and clicks out they do some AJAX work.

Now the problem is this div containing all the element simulates a click on a file input to select an image to update the banner. As the elements are inside, then when I click now on the inputs they also simulate the click on the input file.

What could I do in such case? I've tried setting the z-index for the involved elements, but that doesn't work because the main div, doesn't show nothing nor fires nothing.



let input = document.querySelector('input[name="name"]')
input.onclick = function() {
alert('input pressed')
}
let div = document.querySelector('.main')
div.onclick = function() {
alert('div pressed')
}

.main {
background-image: url('https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg');
width: 640px;
height: 480px;
}

input[name="name"] {
color: white;
background: transparent;
}

<div class="main">
<input type="text" name="name" value="Type here pls">
</div>





This is only JS, not jQuery.

Answer Source

You can use event.stopPropagation() for input, and it will not touch the image:

let input = document.querySelector('input[name="name"]')
input.onclick = function(e) {
  e.stopPropagation();
  alert('input pressed')
}
let div = document.querySelector('.main')
div.onclick = function() {
  alert('div pressed')
}
.main {
  background-image: url('https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg');
  width: 640px;
  height: 480px;
}

input[name="name"] {
  color: white;
  background: transparent;
}
<div class="main">
  <input type="text" name="name" value="Type here pls">
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download