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?

6
  • Use return false in event handler at the end Commented Sep 11, 2015 at 9:31
  • i also use that sorry i forgot to put that it doesnt stop any more Commented Sep 11, 2015 at 9:32
  • 2
    i made a fiddle for you check it out and let me know is this what you want jsfiddle.net/9f8mfpvq/1 Commented Sep 11, 2015 at 9:36
  • Close document.addEventListener(); You are missing ')' I hope Commented Sep 11, 2015 at 9:40
  • 1
    See MDN:Event.stopPropagation(). Commented Sep 11, 2015 at 9:41

1 Answer 1

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/

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

1 Comment

Thanks Ive marked it as the Answer, I cant believe i didnt realise that, nooby mistakes

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.