user8758206
user8758206

Reputation: 2191

Div to toggle it's display on/off but be able to click the input

I'm trying to make it so that whenever you click on either the button OR div itself, the display toggles. But whenever I click on the input inside of the div, the div disappears.

How can this be made so that you can still click on the input and the div not disappear? I've tried setting a z-index to the input but this fails.

Appreciate any help, thank you.

function doThis() {
  var el = document.querySelector('div');
  
  if (el.style.display === 'flex') {
      el.style.display = 'none';
      } else {
        el.style.display = 'flex';
      }
}
div {
  background: lightgreen;
  display: flex;
}
<button onclick='doThis()'>click me</button>

<div onclick='doThis()'>
  text <input type="text">
</div>

Upvotes: 0

Views: 936

Answers (5)

Fii
Fii

Reputation: 317

For a pure JavaScript solution (that doesn't need jQuery), see this answer from @Sabaz to How do I prevent a parent's onclick event from firing when a child anchor is clicked?:

document.getElementById("clickable").addEventListener("click", function( e ){
    e = window.event || e; 
    if(this === e.target) {
        // put your code here
    }
});

Your code wont be executed if clicked on parent's childs

Upvotes: 2

vicbyte
vicbyte

Reputation: 3790

If you want the input click not to trigger the div click, you can use event.stopPropagation() function. It prevents event bubbling (passing the event to higher level DOM-elements).

function doThis() {
  var el = document.querySelector('div');

  if (el.style.display === 'flex') {
      el.style.display = 'none';
      } else {
        el.style.display = 'flex';
      }
}
div {
  background: lightgreen;
  display: flex;
}
<button onclick='doThis()'>click me</button>

<div onclick='doThis()'>
  text <input onclick='event.stopPropagation()' type="text">
</div>

Upvotes: 2

Premshankar Tiwari
Premshankar Tiwari

Reputation: 3106

Just check the target element which is clicked

function doThis() {
 if(event.target.nodeName != "INPUT"){
 var el = document.querySelector('div');
   if (el.style.display === 'flex') {
     el.style.display = 'none';
   } else {
     el.style.display = 'flex';
   }
  }
}

Upvotes: 1

Sarath Kumar
Sarath Kumar

Reputation: 2353

Why cant you implement event stopPropagation for all input objects, Try ..

// select elements with js selectors and bind it
document.querySelector('input').onclick = function(e){
   e.stopPropagation()
};

and here is answer by Rex M

Upvotes: 1

MR0
MR0

Reputation: 164

you can do this:

function doThis(evt) { // <-- new: add argument
  evt.preventPropagation() // <-- new, works in all new browsers
  var el = document.querySelector('div');

  if (el.style.display === 'flex') {
      el.style.display = 'none';
      } else {
        el.style.display = 'flex';
      }
}

And add to your html:

onclick='doThis(event)'

Upvotes: 1

Related Questions