BASILIO
BASILIO

Reputation: 887

Different click event on 2 DIVs that are one in an other

Here is the code that I have tested:

div1 = document.createElement('div');
div1.setAttribute('style','width:500px;height:500px;background-color:green;');
div1.addEventListener('click',function()
    {
    alert('div1');
    });

div2 = document.createElement('div');
div1.appendChild(div2);
div2.setAttribute('style','width:200px;height:200px;background-color:red;');
div2.addEventListener('click',function()
    {
    alert('div2');
    });
document.getElementsByTagName('body')[0].appendChild(div1);

The problem is, that i need only one function call, if i click the div that is inside. I don´t wish to get function from the parent div, how is it possible to make?

Upvotes: 3

Views: 151

Answers (3)

Mircea
Mircea

Reputation: 11623

You need to stop the event propagaton:

var div1 = document.createElement('div');
div1.setAttribute('style', 'width:500px;height:500px;background-color:green;');
div1.addEventListener('click', function () {
    alert('div1');
});

var div2 = document.createElement('div');
div1.appendChild(div2);
div2.setAttribute('style', 'width:200px;height:200px;background-color:red;');
div2.addEventListener('click', function (event) {
    alert('div2');
    event.stopPropagation();
});
document.getElementsByTagName('body')[0].appendChild(div1);

http://jsfiddle.net/KDR9R/1/

Upvotes: 1

abc123
abc123

Reputation: 18853

event.stopPropagation() https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation is what you need to call on the internal div click event this keeps the event from continuing to parent event bindings.

Upvotes: 2

flavian
flavian

Reputation: 28511

You need to use event.stopPropagation().

div2.addEventListener('click',function(event) {
        event.stopPropagation();// prevents  event from bubbling to parents.
        alert('div2');
}, false);

Upvotes: 5

Related Questions