AddEventListener fires automatically upon assignment
addeventlistener, javascript, onclicklistener
Solution
Add `e.stopPropagation()` at the end of your `box` function :
function box(e) {
var pop = document.getElementById("mspop");
pop.style.display = "block";
document.addEventListener("click", clik);
e.stopPropagation();
}
See this fiddle : http://jsfiddle.net/vfyzgv1t/
What is happening is that when you click on your `li` element, the click is then transmitted to the container, and so on up to the window (the so-called event bubbling), and as you have added a event listener on the document (which is between your `li` and the window), it is being triggered.
The solution proposed here, `e.stopPropagation` stops the propagation so that the click on the document is not triggered.
UPDATE : Another way is to delayed shortly the adding of the new eventListener : http://jsfiddle.net/vfyzgv1t/1/ :
function box(e) {
var pop = document.getElementById("mspop");
pop.style.display = "block";
setTimeout(function() {
document.addEventListener("click", clik);
}, 10);
}
Problem
``` <style> #mspop { display:none; } </style> <div> <ul> <li class="check">tem</li> </ul> </div> <div id="mspop" style="background-color:brown;"> <div id="mspopinner"><p id="close">close</p><textarea style="margin: 0px; height: 125px; width: 500px;"></textarea> <button>submit</button> </div> </div> <script type="text/javascript"> (function() { var dec_butt = document.getElementsByClassName("check"); dec_butt[0].addEventListener("click",box); })(); function box(e){ var pop = document.getElementById("mspop"); pop.style.display = "block"; document.addEventListener("click",clik); } function clik(){ var pop = document.getElementById("mspop"); if(event.target != pop){ alert("hi"); pop.style.display = "none"; }; }; </script> ``` The first self invoking function adds a click event listener to the 'li' element with a class 'check' that fires the box function when clicked. Clicking on that 'li' now fires the box function, the box function sets a click event listener to the 'document' object referencing the clik function and also changes display of id 'mspop' to block. However, on clicking the 'li' the addEventlistner assignment of clik also fires clik despite the fact that I have omitted the clik() invocation brackets of the function.