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.
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);
}
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With