1

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 ?

6 Answers 6

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There was a type copy if statement and try again, let me know if it does not work
1

Try like

function fun(x) { document.getElementById(x).style.visibility = (document.getElementById(x).style.visibility != "visible") ? "visible" : "hidden"; } 

Comments

1

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'); } 

3 Comments

i cannot think about a simpler solution
Thanks @R. Oosterholt
@A.Wolff but visibility and display does two different things
0

In jquery :

if($('#div1').is('visible')) { // do something } 

1 Comment

Unfortunately this only works if the element is taking no space (like display:none). It will not work with visibility
0

In jQuery you can use $(x).is(":visible")

function fun(x) { if( $(x).is(":visible") ) { } } 

Comments

0

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' }) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.