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

1
  • learn about event delegation Commented Mar 29, 2013 at 10:44

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

Short answer:

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

Long answer:

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

2 Comments

Thanks for that. Sorry for being a noob. I learn the best from examples!
@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.
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.