16

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.

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39

3 Answers3

23

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);
}
syazdani
  • 4,760
  • 1
  • 26
  • 35
3

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.

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
  • 1
    You're right that the selector is wrong, but the issue is that you cannot call the addEventListener on a collection of elements. – idream1nC0de Aug 22 '15 at 02:41
  • 1
    What if he wanted to attach event handlers to all of the elements? – idream1nC0de Aug 22 '15 at 02:43
  • 1
    I believe he was attempting to add the same event listener to all the elements with one method, which is not possible, seeing as how the collection does not have a method with that name. – idream1nC0de Aug 22 '15 at 02:49
2

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/

idream1nC0de
  • 1,171
  • 5
  • 13