Javscript – Toggle


One use of JavaScript can be to show or hide items on a website at the user’s request. I myself have used it in several of my various web projects. Having grown tired of writing similar code every time, I’ve written a fairly generic function in JavaScript that should work on most types of elements. This function checks if a specified object is displayed or hidden. If the object is hidden, it is displayed, and vice versa. Here’s the code:

function toggle(target_id){
  //Get the element to be displayed or hidden.
  var element = document.getElementById(target_id);

  //Check if the element is hidden.
  if(element.style.display == "none"){
    //If the element is hidden, it should be shown.
    element.style.display = "block";
  //If the element is shown, it should be hidden.
    element.style.display = "none";

Here’s an example of how the function can be used. First create a link that calls the function toggle() when clicked on. The ID of the element you wish to show or hide is sent to toggle() as an argument. Then create the element that the function should be used on. Here is the HTML code:

<button type="button" onclick="toggle('testbox')">Show/Hide</button><br />
<div id="testbox" style="border: 1px #000000 solid; display: none;">
  Text and other content.