Thomas Hermansen
Thomas Hermansen

Reputation: 13

Javascript Show hide

I want to make a show and hide my section.

This is working for now.

But I want my section to be hidden when you enter the site, and then when you click it will show. Right now it is the other way around.

How I can fix this?

 document.querySelector("#about").addEventListener("click", function   (event) {
    event.preventDefault();
}, false);

function showAbout() {
    var myAbout = document.getElementById('about');
    if (myAbout.style.display === 'none') {
        myAbout.style.display = 'block';
    }
    else {
        myAbout.style.display = 'none';
    }
}

Upvotes: 0

Views: 75

Answers (3)

EugenAz
EugenAz

Reputation: 171

You could create a css class:

.hidden {
  display: none;
}

Add this class to your section in html. And then:

document.querySelector("#about")
        .addEventListener("click", function (event) {
           event.preventDefault();
           event.target.classList.toggle('hidden');
        }, false);

Upvotes: 4

nilobarp
nilobarp

Reputation: 4084

In your css put

#about {
    display: none;
}

Upvotes: 1

Win
Win

Reputation: 5584

Wrap an initialiser in a IIFE or add display: none to your element via a default CSS class.

var myAbout = document.getElementById('about');

function showAbout() {
    if (myAbout.style.display === 'none') {
        return myAbout.style.display = 'block';
    }
    return myAbout.style.display = 'none';
}

// Init
(function(){
    myAbout.style.display = 'none';
})();

Upvotes: 0

Related Questions