2

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?

3
  • Also, don't put javascript:toggle() in the href of the link. Commented Jan 13, 2013 at 15:58
  • <a href="#" onClick="toggle()">? Commented Jan 13, 2013 at 18:42
  • Yes, that's ok. But if you only use that element for JavaScript, you should rather use a button and style it as a link if you want to. Commented Jan 13, 2013 at 18:56

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.