Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener is not a function [duplicate]

Tags:

javascript

hi i am trying to close the divs using the close click.. here is the code

var closeIcon=document.getElementsByClassName('.monique-close-icon');  

    function closeBigImgAndContainer()
{
    MoniqueDiv.style.display= "none";
    currentBigImageToDisplay.style.display="none";
};

closeIcon.addEventListener("click", closeBigImgAndContainer);

But in console there is an error Uncaught TypeError: closeIcon.addEventListener is not a function(anonymous function) @ main.js:14 Please tell me where i am doing it wrong...Thanks.

like image 421
Marc Andre Jiacarrini Avatar asked Aug 22 '15 02:08

Marc Andre Jiacarrini


3 Answers

getElementsByClassName returns an array of elements, addEventListener exists on elements.

The fix would be to iterate over the result set from getElementsByClassName and call addEventListener on each item:

var closeIcons=document.getElementsByClassName('.monique-close-icon');  

function closeBigImgAndContainer()
{
    MoniqueDiv.style.display= "none";
    currentBigImageToDisplay.style.display="none";
};

for (i = 0; i < closeIcons.length; i++) {
    closeIcons[i].addEventListener("click", closeBigImgAndContainer);
}
like image 90
syazdani Avatar answered Nov 15 '22 07:11

syazdani


It looks like the closeIcon variable has undefined value.
It is because getElementsByClassName(..) method takes the class name as its parameter.

You can try to fix it as below:

var closeIcons = document.getElementsByClassName('monique-close-icon');
var i = closeIcons.length;
while (i--)
  closeIcons[i].addEventListener("click", closeBigImgAndContainer);

Also the method getElementsByClassName(..) returns a collection of nodes, not a single element. To assign an event listener we need to loop that collection and assign event to each DOM element in it.

like image 31
MaxZoom Avatar answered Nov 15 '22 09:11

MaxZoom


Firstly, your selector is wrong. It should look like this:

var closeIcon = document.getElementsByClassName('monique-close-icon');  

Then you need to append the event handlers as if you were dealing with an Array, as the .getElementsByClassName() method returns a collection of elements.

var closeIcon = document.getElementsByClassName('monique-close-icon'); 
function closeBigImgAndContainer(e)
{
    MoniqueDiv.style.display= "none";
    currentBigImageToDisplay.style.display="none";
};

for (var i = 0; i < closeIcon.length; i++) {
   closeIcon[i].addEventListener('click', closeBigImgAndContainer); 
}

Here's a working example: http://jsfiddle.net/vhe17shd/

like image 2
idream1nC0de Avatar answered Nov 15 '22 07:11

idream1nC0de