• Welcome to The Cave of Dragonflies forums, where the smallest bugs live alongside the strongest dragons.

    Guests are not able to post messages or even read certain areas of the forums. Now, that's boring, don't you think? Registration, on the other hand, is simple, completely free of charge, and does not require you to give out any personal information at all. As soon as you register, you can take part in some of the happy fun things at the forums such as posting messages, voting in polls, sending private messages to people and being told that this is where we drink tea and eat cod.

    Of course I'm not forcing you to do anything if you don't want to, but seriously, what have you got to lose? Five seconds of your life?

Different onClick function for successive clicks?

Lucas₇₅₅

Screw the rules, I have green hair!
Pronoun
he
I'm trying to make a dropdown menu. I've got the scripting right for making the menu appear when you click an arrow, but how can I make it so clicking that same arrow again calls a different function? Here's my code:

HTML:
<html>
<head>
<script type="text/javascript">
function showCMenu(menuId)  {
document.getElementById(menuId).style.display = 'block';
}

function hideCMenu(menuId)  {
document.getElementById(menuId).style.display = 'none';
}
</script>
</head>

<body>
<div id="menu">
<ul>
<li><img src="images/arrow.png" onClick="showCMenu('cmenu1')"><a href="#"></a></li>
<div id="cmenu1">
<a href="#">ipsum</a>
<a href="#">dolor</a>
<a href="#">sit</a>
<a href="#">amet</a>
</div>
</div>
</body>
</html>

Basically, showCMenu works when I click the image, but I need to know how to make the onClick function change after that to call hideCMenu. Any ideas?
 
You don't need to call two functions; you can just have one function with an if statement that checks if the menu is currently visible and shows/hides it accordingly.
 
So:

Code:
function cMenu(menuId)  {
var whatever = 0

if (whatever = 0)  {
document.getElementById(menuId).style.display = 'block'; 
var whatever = 1;
}

else if (whatever = 1)  {
document.getElementById(menuId).style.display = 'none'; 
var whatever = 0;
}}

That would work? I'm a little rusty in javascript, so correct me if I'm calling variables wrong, or misplacing semicolons, or whatever.
 
No, because the var whatever is being re-declared every time the function is called. Ergo, that function runs the same every time.

You want something like this:
Code:
function cMenu(menuId)  {
    var menu = document.getElementById(menuId);
    if(menu.style.display == "block") {
        menu.style.display = "none";
    } else {
        menu.style.display = "block";
    }
}

You can assign the result of getElementById to a variable to make the code cleaner. Also note the double equals signs (==) in the if statement, versus the single equals sign when setting the value. These mean different things, so you can't use a single-equals in an if statement if you want it to run correctly.
 
Back
Top Bottom