mrgerbik2013
mrgerbik2013

Reputation: 97

toggle JavaScript not working

I just want a simple toggle js, so when you click on About in the nav the about text appears, but it's now working oO

JS part:

<script language="JavaScript" type="text/javascript">
function toggle() {
var about = document.getElementById('about')
if(about.style.display = "none")
{
about.style.display = "block";
}

else
{
about.style.display = "none";
}
}
</script>

HTML:

<header>
...
    <nav><ul>
        <li><a href="index.html" id="active">Home</a></li>
        <li><a href="javascript:toggle()" onClick="toggle()">About me</a></li>
        ...more <li>s...
    </ul></nav>
</header>
<br/>

<div id="about">
aboutme
</div>

CSS:

#about {
    display: none;
    }

What am I doing wrong?? Can anybody help me?

Upvotes: 2

Views: 210

Answers (2)

nanobash
nanobash

Reputation: 5500

In if statement you have to have two equal sign

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

Note

= you can just assign value to variable
== must be used to compare variables values
=== must be used to compare variables in every aspect (In type too)

Upvotes: 5

Pointy
Pointy

Reputation: 414006

Fix the == problem, and then instead of hiding your "about" element with that CSS rule put the style directly on the element:

<div id=about style='display: none'>About Me</div>

If you don't do that, the JavaScript code won't see that "display" property on the style object. (The style object only reflects styles directly associated with the element, not those controlled by CSS stylesheets.)

Upvotes: 2

Related Questions