Toggle switches

  1. There's only two parts to this:

    1. writing out the function
    2. Using onclick on an HTML element to use as a toggle switch
  2. The function

    We write out the function to target a div with id of content:

    function toggleContent() {
        let contentId = document.getElementById("content");
    
        contentId.style.display == "block" ? contentId.style.display = "none" : contentId.style.display = "block";
    }
    

  3. The code used:

    1. The block is turned to display: none in the CSS.
    2. getDocumentbyID is used to target the div element which has an: id="content"
    3. ? is combined with the : here. This is the ternary operator: a shorthand of an If / else statement. The first part before the ? is the condition to be met. It is either true or false. The next bit after the question mark, is code to be executed. If it's false the the code after the colon is executed. More...
    4. == means equals
    5. .style to target the CSS of this particular element.
    6. The starting position (ie. hidden) was defined in the CSS for #content.

Toggling classes

It's also possible to toggle classes on an element. In other words adding and then removing a class from an element. This is done using the built in toggle which is part of the classList() method.

See the page on modifying the DOM

It's also possible to toggle the name of a class on an element using className with an if statement.

if (element.className == "myStyle") {
    element.className = "newStyle";
    }
    else {
    element.className = "myStyle";
}