Toggle Multiple Elements Using Javascript Function Parameters
I want to show/hide a div depending on which button is clicked. I tried doing this using parameters of the javascript function but I'm guessing I'm doing it all wrong, so please he
Solution 1:
Here is the HTML code :
<divid="div1">
Content of div1
</div><divid="div2">
Content of div2
</div><buttonid="button"onclick="showhide('div1')">Toggle div1</button><buttonid="button"onclick="showhide('div2')">Toggle div2</button>Here is the javascript code :
<scripttype="text/javascript" >functionshowhide(toggleID){
var toggleDiv = document.getElementById(toggleID);
if(toggleDiv.style.display != "none"){
toggleDiv.style.display = 'none';
}else{
toggleDiv.style.display = 'block';
}
}
</script>
Solution 2:
You have a javascript function which has 2 parameters, and in your HTML you are only sending 1. What you can do is the following:
In the HTML onclick at the buttons:
<button id="button" onclick="showhide('div1')">Toggle div1</button>
<button id="button" onclick="showhide('div2')">Toggle div2</button>
And the javascript function only needs 1 parameter:
functionshowhide(divElement)
{
var div = document.getElementById(divElement);
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
Solution 3:
This is not right:
vardivx="div1";
You can't have space in it:
var div_x = "div1";
You can actually remove both lines and leave it like this:
functionshowhide(x,y)
{
var div = document.getElementById(x);
var div2 = document.getElementById(y);
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
if (div2.style.display !== "none") {
div2.style.display = "none";
}
else {
div2.style.display = "block";
}
}
And call it with:
showhide("div1", "div2");
Solution 4:
Use like this:
<button id="button" onclick="showhide(x,'')">Toggle div1</button>
<button id="button" onclick="showhide('',y)">Toggle div2</button>
And change this:
var div = document.getElementById(x);
var div = document.getElementById(y);
To this:
var div = document.getElementById(x && y); //if x returns x else y
Post a Comment for "Toggle Multiple Elements Using Javascript Function Parameters"