Reputation: 1417
I have 10 divs.By default, the visibility of all of them is set to "hidden". When I click a button,they get visible:
<script>
function fun(x)
{
document.getElementById(x).style.visibility="visible";
}
</script>
<div id="div1" style="visibility:hidden">div1</div><input type="button" value="click" onclick="fun('div1')">
<div id="div2" style="visibility:hidden">div2</div><input type="button" value="click" onclick="fun('div2')">
. . . Is there any way to detect in the fun() function whether a div is visible or hidden so that by examining the state of the div(visible/hidden) it can be made hidden/visible just by clicking the button each time?
My second question is that(first one is already solved): suppose div1 is visible,now I click button number 2,as a result div2 will be also visible,but div1 appears hidden without clicking button number 1 again and so on...How ?
Upvotes: 1
Views: 1791
Reputation: 8080
If jQuery is an option for you, you can use jQuery toggle
Toggle however toggles display (not visibility); if this is ok for you try:
function fun(x) {
$("#"+x).toggle();
}
jQuery solution for toggling the visibility:
function fun(x) {
var $obj = $("#"+x);
$obj.css('visibility', $obj.css('visibility')=='hidden'?'visible':'hidden');
}
Upvotes: 1
Reputation: 388316
Try
function toggle(x) {
var style = document.getElementById(x).style;
style.visibility = style.visibility == "visible" ? 'hidden' : 'visible'
}
or jQuery equivalent
function toggle(x) {
$('#' + x).css(visible, function (_, visibility) {
return visibility == "visible" ? 'hidden' : 'visible'
})
}
Upvotes: 0
Reputation: 148110
You can get value of property visibility
and compare it with its possible values.
function fun(x)
{
if( document.getElementById(x).style.visibility == "visible")
document.getElementById(x).style.visibility = "hidden";
else
document.getElementById(x).style.visibility = "visible";
}
If you can use jQuery then you can use show()
, hide()
functions but they use display
property instead of visibility
.
Upvotes: 1
Reputation: 10703
In jQuery you can use $(x).is(":visible")
function fun(x)
{
if( $(x).is(":visible") ) {
}
}
Upvotes: 0
Reputation: 28763
Try like
function fun(x)
{
document.getElementById(x).style.visibility =
(document.getElementById(x).style.visibility != "visible") ? "visible" : "hidden";
}
Upvotes: 1