Saturday, March 14, 2009

CSS Hidden Div (2)



The first example I posted to hide a div using javascript and css, was a href link and can be seen here. This time I will use an image, and the image will also change to denote that the div should be expanded/collpased. As you can see from the other example, I'll keep the exact same code for hidding/showing the div. The additional step this time is to use the getElementById tag to dynamically change the source of the image.
So the additional parameter I send in the javascript method is the id of the image to change. The tricky part is when you grab the image source, you get the full path. This is not ideal for code you want to work across all environments, so the best option here is when you grab the full source, to split it up and just use the 'images/arrow-right.jpg' part of the string.
The split method creates an array of the objects that are separated by '/' in the url, therefore I just need to grab the last 2 array elements and insert a / to reconstuct the shortened url.

<script language="javascript">
function switchDiv(divId, arrowId) {

if ( document.getElementById(divId).style.display != 'none' ) {
document.getElementById(divId).style.display = 'none';
}
else {
document.getElementById(divId).style.display = 'block';
}
var imagePath = document.getElementById(arrowId).src
var splitPath = imagePath.split("/");
var path = splitPath[splitPath.length-2] + '/' + splitPath[splitPath.length-1];
if ( path != 'images/arrow-right.jpg' ) {
document.getElementById(arrowId).src = 'images/arrow-right.jpg';
}
else {
document.getElementById(arrowId).src = 'images/arrow-down.jpg';
}
}
</script>

Here is the call in the HTML:
<div class="title">
<a href="javascript:switchDiv('arrangements', 1)"><img id="1" src="images/arrow-down.jpg"/></a> Title
</div>
<div id="hiddendiv">
<table style="border:1px solid black; margin-left:10px;">
<tr><td>Div is now showing</td></tr>
</table>
</div>

No comments:

Post a Comment