PDA

View Full Version : Show/Hide/Toggle



ReadyToLearn
02-29-2008, 05:22 PM
Here is the script I'm working with:


<script type="text/javascript">
<!--
function show(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}


function toggle(x){
if(x.src== 'images/plus.gif')
x.src = 'images/minus.gif';
else
x.src = 'images/plus.gif';
}
//-->
</script>

Each of these functions works independently (well, kind of).

1. I'd like to combine these two. Bascially, when a div is showing (display:block) i'd like for the image to be minus.gif and of course the opposite to be true.

2. The toggle function only works once. The image is initially minus.gif. When I click it it turns to plus.gif but when I click it again it doesn't change. If I initially use plus.gif, it doesn't work at all.

these are both onClick events on the image itself. In the case of the latter (toggle) function, I'm using "this" whereas in the show function i'm using the id of the div.

Thanks for the help :)

Bob90
03-03-2008, 03:22 PM
function toggle(obj) {
re = /first_image.jpg$/
if(obj.src.match(re)) {
obj.src = 'second_image.jpg';
}
else {
obj.src = 'first_image.jpg';
}
}


This code takes an image object, searches the image source for the name of the file and changes it to the appropriate one.



//the toggle function
function toggle(obj) { //pass the img object to the function
//create a 'regular expression' to search for the filename. The $ means it will search the end of the string
re = /first_image.jpg$/
//test for a match
if(obj.src.match(re)) {
//if it matches use the second image
obj.src = 'second_image.jpg';
}
else {
//if it does not match use the first image
obj.src = 'first_image.jpg';
}
}
//Remember to include the file extension (.gif .jpg)

Bob90
03-03-2008, 03:27 PM
function toggleBoth(obj, id) {
//Image toggle
re = /first_image.jpg$/
if(obj.src.match(re)) {
obj.src = 'second_image.jpg';
}
else {
obj.src = 'first_image.jpg';
}
//Div toggle
var el = document.getElementById(id);
if(el.style.display == 'block') {
el.style.display = 'none';
}
else {
el.style.display = 'block';
}


}

codeexploiter
03-05-2008, 05:15 AM
Check the following code



var toggleBoth = function(id, imgElm){
var d = document;
if(imgElm.src == 'img/plus.gif'){
imgElm.src = 'img/minus.gif';
d.getElementById(id).style.display = 'block';
}else{
imgElm.src = 'img/plus.gif';
d.getElementById(id).style.display = 'none';
}
}


Image file name and path should be adjusted for your requirement.