I'm working on a personal website and I'm trying to have a show/hide on click of an image, but I'm not really sure where the problem is.
HTML
<div id="menuopen">
<a href="#" onclick="toggle('menu');">
<img src="assets/Images/menu.gif" alt="Menu">
</a>
</div>
<div id="menu">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html">Home</a></li>
<li><a href="index.html">Home</a></li>
<li><a href="index.html">Home</a></li>
</ul>
</div>
JS
<script type="text/javascript">
<!--
function toggle(id) {
var item = document.getElementById(id);
if(item.style.display == 'block')
item.style.display = 'none';
else
item.style.display = 'block'; }
//-->
As a side note, this script also did not work using plain text rather than the image, so I don't think that my problem lies there.
Check this one. Just a short explanation, your function is checking if the element has a block
value attached to it's display property which is wrong - by default this property is empty. So, rather ask for none
or an empty
(default) value.
function toggle(o) {
var e = document.getElementById(o);
e.style.display = (e.style.display != 'none' ? 'none' : '' );
}
Sometimes the style properties are empty/meaningless until they have been set in JavaScript. You can either set the value in JS first or you can have your JS assume the starting state.
Solution 1 - Set state from JS:
var s = document.getElementById('menu').style;
s.display = 'block';
function toggle() {
if(s.display == 'block') { s.display = 'none'; }
else { s.display = 'block'; }
}
Solution 2 - Assume unset means it's visible
function toggle(id) {
var s = document.getElementById('menu').style;
s.display = (s.display!=='block' ? 'block' : 'none');
}
I don't have a lot of time to analyze, but I'd recommend using an in-body function with a click trigger instead of pre-defining the function. Something like what's in the fiddle here :
Hope this helps, let me know if you want some clarification and I'll do what I can.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.