0

I have issue with addEventListener on click, the problem is on first I have to click twice in order to show/hide the div. After the first click, the form is showing/hiding on every click. How can I fix this?

document.getElementById("setter-arrow-right").addEventListener("click", function() {
  if (document.getElementById("setter-container").style.width == "4vw") {
    document.getElementById("setter-container").style.width = "95vw";
    document.getElementById("setter-back").innerHTML = `<`;


    document.getElementById("scrap-container").style.display = "none";

  } else {
    document.getElementById("setter-container").style.width = "4vw"
    document.getElementById("setter-back").innerHTML = `>`;
    document.getElementById("scrap-container").style.display = "block";
  }
});
<div id="setter-scrap-container">
  <!-- Setter View -->
  <div id="setter-container">
    <!-- Button Right -->
    <div id="setter-arrow-right">
      <p>SETTER</p>
      <span id="setter-back">
        <p>></p>
      </span>
    </div>
  </div>
  <!-- Scrap View -->
  <div id="scrap-container">
    <!-- Button Left -->
    <div id="scrap-arrow-left">
      <p>SCRAP</p>
      <span id="scrap-back">
        <p><</p>
      </span>
    </div>
  </div>
</div>
Andy
  • 61,948
  • 13
  • 68
  • 95
Kate
  • 19
  • 4
  • Dont base if conditions on style, use a boolean to track the show/hide status. I guess your element is missing the style at first, so it doesnt work. – Lk77 Dec 15 '22 at 10:09
  • It's also worth noting that paragraph elements aren't permitted [inside of span elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span#technical_summary). – Andy Dec 15 '22 at 10:11
  • And also retrieve the element from the event, with event.target, dont use getElementById again, there is no need to, you already have it. – Lk77 Dec 15 '22 at 10:12
  • @Andy, I add paragraph to remove the SVG's < or >. – Kate Dec 15 '22 at 10:20
  • @Lk77 how can I use boolean to track the show/hide status? I don't want to simple show the elements and disappear. Just slide from one side to another and opposite. It does work after the second click – Kate Dec 15 '22 at 10:22
  • well simply define a variable in your js with the default value, like `let arrowRightShow = true;`. And use arrow functions to access it : `() => {}` , normal function do not work with local variables, you will be forced to use global `var` instead – Lk77 Dec 15 '22 at 10:23

0 Answers0