0

I have this code:

<td onclick="Test()">
  <img src="test.jpg" onclick="Test2(); return false;"><br>
  Rest of the cell with some text.
</td>

When I click the image, Test() is also fired because I am also clicking the table cell. How to provent this? If I click on the image, I want test2() to fire, if I click somewhere else in the table cell, test() should be fired.

Edit: Even with return false, Test() is still fired(testing in Chrome)!

Mbrouwer88
  • 2,182
  • 4
  • 25
  • 38

3 Answers3

6

If Test2() returns false the click won't bubble to Test()

Horen
  • 11,184
  • 11
  • 71
  • 113
fmsf
  • 36,317
  • 49
  • 147
  • 195
3

Short answer:

<img src="test.jpg" onclick="Test2(); return false;">

Long answer:

Event Order - http://www.quirksmode.org/js/events_order.html

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Thanks for that. Sorry for being a noob. I learn the best from examples! – Mbrouwer88 Mar 24 '13 at 22:15
  • @Mbrouwer88 - in that case you have a JavaScript error in your Test2( function which is causing script execution to halt before it gets to your return false statement. In Chrome or Firefox, open up your console or Firebug (CTRL+SHIFT+J) and click on the image - you'll see a script error. Fix it. – Adam Jenkins Mar 29 '13 at 11:50
1

The way I prefer is using eventListeners and event.stopPropagation() as I've read some browsers do not accept return false and it's also not a very well defined action. And like Adam said, it's worth it to read up on event propagation.

<div id="clickme"></div>

<script>
document.getElementById("clickMe").addEventListener("click", function(event) {
  event.stopPropagation();
  //event.preventDefault();  this is the same as return false;
});
</script>
Community
  • 1
  • 1
Seph Reed
  • 8,797
  • 11
  • 60
  • 125