Forum Moderators: open
HTML
<div id="mydiv"><a href="javascript:unhide('mydiv2');">Click here to show content</a>
</div>
<div id="mydiv2" class="hidden"> this hidden text will show when the link is pressed
</div>
CSS
.hidden { display: none; }
.unhidden { display: block; }
JAVASCRIPT
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
window.onload=function() { document.onclick=function() { document.getElementById('mydiv').style.display='none'; }; };
</script>
</head>
<body>
<p id="mydiv">Click and hide me</p>
<p>I won't hide.</p>
</body>
</html>
</html>
You would just change
window.onload=function() { document.onclick=function() { document.getElementById('mydiv').style.display='none'; }; };
to
window.onload=function() { document.onclick=function() { unhide('mydiv'); }; };
Thanks for the previous code though. At least i'm getting somewhere.
Javascript in a page is not "aware" of the class of an item unless it's an inline selector; see this thread [webmasterworld.com] and link within it to sort out why. So you have to specifically set the class in the window.onload to get it to "know" what the initial load state is.
This should do it, using your classes (works here.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- doctype on one line -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
.hidden { display: none; }
.unhidden { display: block; }
</style>
<script type="text/javascript">
window.onload=function() {
if (document.getElementById('mydiv')) {
document.onclick=function() { unhide('mydiv'); };
document.getElementById('mydiv').className=='unhidden';
}
};
function unhide(divID) {
if (document.getElementById(divID)) {
var item = document.getElementById(divID);
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
</head>
<body>
<p id="mydiv">Click and hide me</p>
<p>I won't hide.</p>
</body>
</html>
As oft said, there's always more than one way to do it - for a simple show/hide, I wouldn't refer to the class name - what if you want to use this again on a site without these particular selectors? I'd just toggle the display:
if (document.getElementById(divID)) {
var item = document.getElementById(divID);
item.style.display=(item.style.display=='block')?'none':'block';
}