Skip to content Skip to sidebar Skip to footer

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. H

Solution 1:

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).

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

  if (el.style.display === 'flex') {
      el.style.display = 'none';
      } else {
        el.style.display = 'flex';
      }
}
div {
  background: lightgreen;
  display: flex;
}
<buttononclick='doThis()'>click me</button><divonclick='doThis()'>
  text <inputonclick='event.stopPropagation()'type="text"></div>

Solution 2:

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

Solution 3:

you can do this:

functiondoThis(evt) { // <-- new: add argument
  evt.preventPropagation() // <-- new, works in all new browsersvar 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)'

Solution 4:

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

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

and here is answer by Rex M

Solution 5:

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';
   }
  }
}

Post a Comment for "Div To Toggle It's Display On/off But Be Able To Click The Input"