N. deSaillan N. deSaillan - 22 days ago 9
Javascript Question

Using .getElementsByClassName to access multiple popups

I am attempting to use the following javascript to create various popups.Image popups when text is clicked. The problem is that when I click any of the text containers, all of the popup images appear. I know I am missing something obvious. Any help would be much appreciated. Here is the JS code:

function myFunction() {

var popup = document.getElementsByClassName("myPopup");

for(var i=0; i<popup.length; i++) {

popup[i].classList.toggle('show');
}
}


HTML:

<div class="popup" onclick="myFunction()"><span class="castName">Viola,</span>
<span class="popuptext myPopup"><img src=Viola_1.jpg
style="width:300px;height:100%;" alt="Viola"><p>Miss Ellen Terry as Viola, mid
to late 19th century</p></span></div>

Answer

Your function gets a list of elements and toggle the class 'show' to every element instead of the element you want. You have to pass in the element to the function.

You can change the onclick event for each div from:

<div class="popup" onclick="myFunction()">

to:

<div class="popup" onclick="myFunction(this)">

Then in your javascript

function myFunction(element){
    if (element){ //If the element is passed into this function
        element.getElementsByClassName("myPopup")[0].toggle('show');
    }
}
Comments