John Hudson
John Hudson

Reputation: 449

Javascript DOM Onclick event trigger for single element

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?

Upvotes: 0

Views: 788

Answers (1)

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

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/

Upvotes: 1

Related Questions