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

events, javascript

Solution

You need to use `event.stopPropagation()`.

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

Problem

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?

Original source