0

Basically ive got a page, the code:

<body>
    <div onclick="alert('You clicked ' + this.tagName)">
       <h1 onclick="alert('You Clicked ' + this.tagName)">Click Me</h1>
    </div>
</body>

This is not my exact script but i rebuilt it for demonstrational purposes, when I click on the H1 it alerts like it should but when I close the alert box the DIV comes up , I have tried another way round it where I had

document.addEventListener('click' , function(e){
     var target = e.target || e.srcElement;
     alert('You Clicked ' + target.tagName);
});

This didn't work on all Elements of the page for some elements on the page for a weird reason is the a reason for this, am I missing something?

intekhab
  • 1,566
  • 1
  • 13
  • 19
John Hudson
  • 429
  • 1
  • 3
  • 11
  • Use `return false` in event handler at the end – Tushar Sep 11 '15 at 09:31
  • i also use that sorry i forgot to put that it doesnt stop any more – John Hudson Sep 11 '15 at 09:32
  • 2
    i made a fiddle for you check it out and let me know is this what you want http://jsfiddle.net/9f8mfpvq/1/ – Shailendra Sharma Sep 11 '15 at 09:36
  • Close document.addEventListener(); You are missing ')' I hope – intekhab Sep 11 '15 at 09:40
  • 1
    See [*MDN:Event.stopPropagation()*](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation). – RobG Sep 11 '15 at 09:41
  • return false is not really the correct way, to stop event propagation as per RobG and Shailendra Sharma's suggestions is definitely the way to go. To read more about it, please [view this SO post](http://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery) and [this one as well](http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false) – Ibanez Sep 11 '15 at 09:58

1 Answers1

1

That is because After an event triggers on the deepest possible element, it then triggers on parents in nesting order

You need to stop event propagation in your case

 <body>
        <div onclick="alert('You clicked ' + this.tagName)">
           <h1 onclick="alert('You Clicked ' + this.tagName);event.stopPropagation();">Click Me</h1>
            xcxc
        </div>
    </body>

here the fiddle : http://jsfiddle.net/9f8mfpvq/1/

Shailendra Sharma
  • 6,976
  • 2
  • 28
  • 48