Show and Hide

Using JavaScript its important to be able to show or hide a specific element. The element in question will typically have an ID, and clicking either that object, or another object, will show or hide the object with the ID.

An image is required that can be shown and hidden when the buttons are clicked. This image will need an ID that the JavaScript can reference.

<!-- This is the image that can be shown and hidden. -->
<img src="mainImage.png" id="imageToShowAndHide">

Two additional images are required. Clicking each image will have an onclick event which calls a function.

  • One function will show an image.
  • The other function will hide an image.
<!-- Clicking this image calls the ShowImage() function -->
<img src="showImage.png" onclick="ShowImage()">

<!-- Clicking this image calls the HideImage() function -->
<img src="hideImage.png" onclick="HideImage()">

Finally, two JavaScript functions are needed that use the exact same function names as the show and hide images.

//This function is called when the Show Image is clicked
function ShowImage(){
    // Finds the element with the id 'imageToShowAndHide and sets its display to block
    document.getElementById("imageToShowAndHide").style.display = "block";
}

//This function is called when the Hide Image is clicked
function HideImage(){
    // Finds the element with the id 'imageToShowAndHide and sets its display to none
    document.getElementById("imageToShowAndHide").style.display = "none";
}

This same logic can be applied to any element; to hide divs and sections. The code just needs to reference the element by ID and set its display to none or block as necessary.