/    Sign up×
Community /Pin to ProfileBookmark

expand collapse menu problem( using divs )

Ok, so from reading the javascript phase book i wrote this small function to expand/collapse div for menus:

[CODE]
function ExpandCollapseById(div_id)
{
var element = document.getElementById(div_id);

if(element.style.display != “block”)
{
element.style.display = “block”;
}
else
{
element.style.display = “none”;
}

return false;
}
[/CODE]

now if a menu is set tpo be collapsed by default( ex display: none; ) the function works fine but if the menu is expanded by default(ex display: block; ) I have to click on the link 2 times to get is to work. does anyone know what could cause this, is there anything wrong with my code.

the html code is:

<a class=”white_link” href=”javascript:void(0);” onclick=”ExpandCollapseById(‘links’);”>

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@OverstatementJan 03.2007 — Because when you go != 'block' it means DOES NOT EQUAL 'block', it doesn't mean DOES EQUAL 'none'. When you run this function the first time, your element will have the default style.display value of ""(nothing) which, of course, DOES NOT EQUAL 'block'. Therefore, the first run of your function will always try to show your div. So if your div is shown by default and your function shows your already shown div and you won't notice a difference. If you hid your div by default, your first run will show your div.

How do you fix it? You could try writing your div like this:
[code=html]
<div id="MyDiv" style="display:none"></div>
[/code]

If that doesn't work, try putting this code into the body of your page somewhere after your div
<i>
</i>&lt;script type="text/javascript"&gt;
document.getElementById("MyDiv").style.display = 'none';
&lt;/script&gt;
Copy linkTweet thisAlerts:
@RyanZecauthorJan 03.2007 — The first method worked. why will is only work if i declare the css in the html code and not the seperate css file?
Copy linkTweet thisAlerts:
@OverstatementJan 03.2007 — Because browsers are stupid. Or maybe I'm too stupid to think of a reason why this happens.
×

Success!

Help @RyanZec spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...