Why does the onclick button work only once in javascript?

Asked 1 years ago, Updated 1 years ago, 65 views

Using the class attribute, I solved the practice problem that the menu bar appears and disappears when I press the button, but if I press the button, it works at first, but it doesn't work next timeWhat's the problem?

It's the chords▼

<!DOCTYPE html> Page 3D

    header{
        width: 600px;
        height: 190px;
        border: 1px solid #ccc;
        background: #ccc;
    }

    #toggle{
        position: absolute;
        left: 400px;
        top: 90px;
        outline: none;
        background: #666;
        color: white;
        font-size: 20px;
        padding: 0 5px;
        text-decoration: none;
    }
    #toggle:hover{text-decoration: underline; }

    #gnb.active{
        height: 190px;
    }
    #gnb{
        width: 200px;
        height: 0px;
        overflow: hidden;
        border-bottom: 1px solid #666;
        border-top: 1px solid #ccc;
        box-sizing: border-box;
        transition-duration: 0.5s;
    }
</style>

app title toggle

    <nav class="active" id="gnb">
        <div><a href="#" class="menu">Home</a></div>
        <div><a href="#" class="menu">Profolio</a></div>
        <div><a href="#"class="menu">Contact</a></div>
    </nav>

var toggle = document.getElementById('toggle');
var gnb = document.getElementById('gnb');
var attr = gnb.getAttribute('class');

toggle.onclick = function(){

    if (attr == 'active'){
        gnb.removeAttribute('class');
        return false;

    }else{
        gnb.setAttribute('class','active');
        return false;
    }
}

javascript onclick

2022-09-22 20:56

1 Answers

The getAttribute function is a function that gets the "current" attribute. In other words, calling setAttribute below does not change the value of the attr variable.

Let me add that there's a function like this.

gnb.classList.toggle('active')

gnb.classList.add('active')
gnb.classList.remove('active')

Preview

https://codepen.io/RedPumpkin/details/JORoMY/


2022-09-22 20:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.