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";
    }
    

    The button tag uses onclick. Any element could be used, not just <button>

    And onclick="toggleContent()" where toggleContent is the function we wrote.

    This came from Wikihow.com

  3. The key bits of javascript used:

    • getDocumentbyID to target the div element with id="content"
    • ? is combined with the : here. What it is saying is a kind of shorthand of an If / else statement. Specifically the statement preceding it is either true or false. If it's true return the value after the question mark. If it's false return the value after the colon. More...
    • ==
    • .style to target the CSS of this particular element.
    • The starting position (ie. hidden) was defined in the CSS for #content.