0

How can I prevent the default onClick behavior for an <input>?

document.getElementById("main").onclick = function() {
  document.getElementById("main").style.backgroundColor = "red";
}
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red.
  <input id="search" type="search" value="If you click here, do nothing.">
</div>

Working example: https://jsfiddle.net/7bng6zuh/3/

adiga
  • 34,372
  • 9
  • 61
  • 83
Jack
  • 365
  • 2
  • 14
  • 1
    Does this answer your question? [How to prevent default event handling in an onclick method?](https://stackoverflow.com/questions/7056669/how-to-prevent-default-event-handling-in-an-onclick-method) – evolutionxbox Jan 09 '20 at 14:40
  • 2
    [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga Jan 09 '20 at 14:43

2 Answers2

1

To prevent your div from changing it's background when the input is clicked and only change it when the div is directly clicked, just compare the event target with the event current target (the element you added the click listener to) and change the div css only if the target is the same as the current target like this:

const mainDiv = document.getElementById("main");

function checkClick(e) {
 if (e.target === e.currentTarget) { // check if element clicked is the div itself or some other element in the div.
   mainDiv.style.backgroundColor = "red";
  }
}

mainDiv.addEventListener('click', checkClick);
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red. 
  <input id="search" type="search" value="If you click here, do nothing.">
</div>

Event Target: The element you clicked.

Event Current Target: The element that the click listener is listening to.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
0

Check the target:

document.getElementById("main").addEventListener("click",function(e) {
  if (e.target.id && e.target.id  === "main") { // or e.target === e.currentTarget
    this.style.backgroundColor = "red";
  }
});
#main {
  background-color: blue;
}
<div id="main">
  If you click here, change background to red. 
  <input id="search" type="search" value="If you click here, do nothing.">
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236