Search code examples
javascripthtmlshow-hide

Hiding text with JS


I asked this in another thread and got some helpful advice. I'm re-posting this because I'm not getting any traction on the other post.

I have a small line of html that opens a side nav bar:

<div id="main">
        <span id="open" style="font-size:30px;cursor:pointer">&#9776; Open</span>
        <img class="imgcenter" src="/images/eggs.jpg">
        <p>Where </p>
        <img class="imgcenter" src="/images/eggs.jpg">

      </div>

The corresponding js for this html that is supposed to show hide "Open" when ☰ Open is clicked:

document.getElementById("open").addEventListener("click", function openMainNav() {
document.getElementById("myMainNav").classList.add('sideNavOpen');
document.getElementById("main").classList.add('lmarg250');
var x = document.getElementById("open");
if (x.innerHTML === "&#9776; Open") {
  x.innerHTML = "&#9776;";
} else {
  x.innerHTML = "&#9776; Open";
}

});

I was instructed to remove the "onclick" inside the hmtl because it is in-secure and also my var x wasn't defined so I've defined it. I've fixed both but I'm un-able to get the "Open" text to hide. I believe the problem lies in how i've grouped my elements or how i'm assigning my ID's? Any suggestions would be greatly appreciated.


Solution

  • I simplified your question a little. You are comparing a charcode to a string representation of the charcode. You can use String.fromCharCode() to get the character and match it.

    document.getElementById("open").addEventListener("click", function() {
      let span = document.getElementById("open");
      if (span.innerHTML === String.fromCharCode(9776).concat(" Open") )
        span.innerText = String.fromCharCode(9776);
      else
        span.innerText = String.fromCharCode(9776).concat(" Open");
    
    });
    <span id="open" style="font-size:30px;cursor:pointer">&#9776; Open</span>

    PS: If you are using a callback function there is no need to name it.