N. deSaillan N. deSaillan - 1 year ago 73
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++) {



<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 Source

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()">


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

Then in your javascript

function myFunction(element){
    if (element){ //If the element is passed into this function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download