Home > other >  Why does the toggle only works after the second click? (Repost)
Why does the toggle only works after the second click? (Repost)

Time:03-04

I just want to do a simple toggle on the details with the tag "typesDetails" and to change the name of the button from "Hide" to "Show". Both functions seems to work but the toggle by itsself triggers after the second click while the name changing works on the first click. Does anybody know why the toggle dont work on the first click?

JS:

    var xa = document.getElementById('tglFold');
    xa.addEventListener('click', function (e) {
        var btn = document.getElementById("tglFold")
        if (btn.value === "Hide")
            btn.value = "Show";
        else
            btn.value = "Hide";

        e.target.classList.toggle('exp');
        e.target.classList.toggle('col');
        var details = document.querySelectorAll("#typesDetails");
        Array.from(details).forEach(function (obj, idx) {
            if (e.target.classList.contains('exp')) {
                obj.open = true;
            } else {
                obj.open = false;
            }
        });
    }, false);

HTML:

<input type="button" value="Hide" id="tglFold" />

The previous question has been closed due a typo which didnt caused the issue.

CodePudding user response:

var xa = document.getElementById('tglFold');
    xa.addEventListener('click', function (e) {
        var btn = document.getElementById("tglFold")
        if (btn.value === "Hide"){
            btn.value = "Show";
         }
        else {
            btn.value = "Hide";
         }
        e.target.classList.toggle('exp');
        e.target.classList.toggle('col');
        var details = document.querySelectorAll(".typesDetails");
        Array.from(details).forEach(function (obj, idx) {
            if (e.target.classList.contains('exp')) {
                obj.style.display = 'none';
            } else {
                obj.style.display = 'block';
            }
        });
    }, false);
.typesDetails{
  display: block;
}
<input type="button" value="Hide" id="tglFold" />


<div class='typesDetails'>1</div>
<div class='typesDetails'>2</div>
<div class='typesDetails'>3</div>
<div class='typesDetails'>4</div>
<div class='typesDetails'>5</div>

I think the error was with your if statement.....since you didn't have the { } closing the if and else blocks of your condition the code after the btn.value = "hide" line was only getting executed when the btn.value was equal to "Show"....since it starts with "Hide" only btn.value = "show" was executing and the else block never ran....I added the { } and tested ...I also changed the querySelector to select by class instead of id.....you aren't supposed to have multiple elements with the same id ....I think this is the effect you are going after

  • Related