skip to Main Content

I have a link on a page which causes a <div id="po" style="display:none;">some html</div> to show or hide. The first time the hide/show link is clicked, the div is displayed. Any time after that, the link does nothing and I don’t see why. I did try conversely setting the <div style="display:block;"> and clicking the link caused the div to hide. Subsequently, the div would not show. I am not seeing why this does not work. I have the exact same thing elsewhere on the page and that div toggles.

function po() {
  po = document.getElementById('po').style.display;
  
  if (po == "none") {
    document.getElementById('po').style.display = 'block';
    document.getElementById('po_Menu').src = "images/menu_dash.jpg";
  } else {
    document.getElementById('po').style.display = 'none';
    document.getElementById('po_Menu').src = "images/menu_plus.jpg";
  }
}
<img id="po_Menu" src="https://via.placeholder.com/50"> <a href="po()">show/hide</a>

2

Answers


  1. You’re clobbering the function here:

    po = document.getElementById('po').style.display;
    

    This assigns a new value to po, so future calls to po() will fail because it’s no longer a function.

    Declare a new variable instead:

    const disp = document.getElementById('po').style.display;
    
    Login or Signup to reply.
  2. Besides the naming conflict/overwriting that you’re doing with po, you should avoid inline styles and instead use CSS classes, which reduce the amount of code you’ll need to write (see the omission of the if statement below) and only use hyperlinks for navigation.

    See additional comments inline:

    const po = document.getElementById('po');
    
    // Anything that is visible can have a "click" event handler added to it:
    document.querySelector("#toggle").addEventListener("click", function() {
      // When you use classes, you get to do more with less code:
      po.classList.toggle("hidden");
    });
    /* Use CSS classes instead of inline styles whenever possible */
    #toggle { text-decoration:underline; color:blue; cursor:pointer; }
    .hidden { display:none; }
    <img id="po_Menu" src="https://via.placeholder.com/50">
    
    <!-- Don't use hyperlinks as JavaScript "hooks". Hyperlinks are for navigation. -->
    <span id="toggle">show/hide</span>
    
    <!-- Avoid inline styles whenever possible and use classes instead. -->
    <div id="po" class="hidden">some html</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search