Search code examples
javascripthtmlcssvisible

Toggle Visibility Not Working (HTML/CSS/Javascript)


I am following this tutorial from W3Schools on how to build a slideshow using HTML, CSS, and Javascript. On the website I am developing, I would like the thumbnails at the bottom and the arrows on the sides to be initially hidden, until the user presses a button.

To do so, in the CSS file, I have set the visibility: hidden;. The CSS code for the class dot, which is the bottom thumbnail, is as follows:

.dot {
    cursor: pointer;
    height: 15px;
    width: 15px;
    margin: 0 2px;
    background-color: #bbb;
    border-radius: 50%;
    display: inline-block;
    visibility: hidden;
    transition: background-color 0.6s ease;  
}

In the Javascript action for the button, I have set the visibility of the document's elements under the class "dot" to visible, like so:

document.getElementsByClassName("dot").style.visibility="visible";

I have verified that this action is being triggered when the button is pressed through an alert() view. Every line of code seems to run as intended up until this command. Also, the thumbnails at the bottom (the "dot" elements) do not appear, so their visibility does not become visible as intended.

Any ideas on why this may be, or how I can fix it? Thanks a lot for your help!


Solution

  • This document.getElementsByClassName("dot") returns an array and you cannot apply a style attribute to the array.

    I'll give you a couple ideas about how you might approach or reconsider this problem.

    1) loop through the array and apply a style to each element

    var elements = document.getElementsByClassName("dot")
    for(var i = 0; i < elements.length; i++) {
        elements[i].style.visibility = "visible";
    }
    

    2) give an ID to each class and call document.getElementById("someID")

    <div id="one">one</div>
    <div id="two">two</div>
    <div id="three">three</div>
    
    document.getElementyById("one").style.visibility = "visible";
    document.getElementyById("two").style.visibility = "hidden";
    document.getElementyById("three").style.visibility = "hidden";