Skip to content
Advertisement

JavaScript 2 onclick Events but just do the first

I have a JavaScript functions which get run 2 times when I click on one element. Take a look at my code, I only want that the first call will be done not the second also:

<p class="chat" onclick="Open('chat')">
 <img class="chatpicture" src="jpg/1.jpg" onclick="Open('user')">
</p>

When I click on the image then also the p element with his onclick function will be run. Because the image onclick is inside the p element which also have onclick.

What is the best way to only let the image onclick run and not at same time also run the p element onclick?

Advertisement

Answer

You can try using Event.stopPropagation():

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.

Demo:

function Open(inputVal){
  event.stopPropagation();
  console.log(inputVal);
}
<p class="chat" onclick="Open('chat')">
  <img class="chatpicture" src="jpg/1.jpg" onclick="Open('user')">
</p>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement