Reputation: 23
I have a page with several buttons and an associated text div. I can toggle the visibility of the text div by clicking each button. I would like to get the visibility of each text div and use it to re-produce the page state. How do I get the “visibility” of the text divs?
My code so far only responds with “visible”.
Many thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Visibility</title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
function getVis(textDiv){
if ($(textDiv).is(":visible")) {
alert("visible");
}else{
alert("not visible");
}
}
</script>
</head>
<body>
<button id="btn1" onclick="$(div1).slideToggle(500), getVis(div1)">button 1</button>
<div id = "div1">div 1 text</div>
<br>
<button id="btn2" onclick="$(div2).slideToggle(500), getVis(div2)">button 2</button>
<div id = "div2">div 2 text</div>
</body>
</html>
Upvotes: 0
Views: 33
Reputation: 4963
Due to slideToggle
being a transition (over time operation), check visibility prior to invoking the transition, i.e. reverse the call order. For example
<button id="btn1" onclick="getVis(div1), $(div1).slideToggle(500)">button 1</button>
Here's a demo.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Visibility</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function getVis(textDiv){
if ($(textDiv).is(":visible")) {
alert("visible");
}else{
alert("not visible");
}
}
</script>
</head>
<body>
<button id="btn1" onclick="getVis(div1), $(div1).slideToggle(500)">button 1</button>
<div id = "div1">div 1 text</div>
<br>
<button id="btn2" onclick="getVis(div2), $(div2).slideToggle(500)">button 2</button>
<div id = "div2">div 2 text</div>
</body>
</html>
To determine the visibility state after the transition, call getVis
from the completion routine like so
<button id="btn1" onclick="$(div1).slideToggle(500, function() { getVis(div1) })">button 1</button>
Here's a demo of the completion approach.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Visibility</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
function getVis(textDiv){
if ($(textDiv).is(":visible")) {
alert("visible");
}else{
alert("not visible");
}
}
</script>
</head>
<body>
<button id="btn1" onclick="$(div1).slideToggle(500, function() { getVis(div1) })">button 1</button> <div id = "div1">
div 1 text
</div>
<br>
<button id="btn2" onclick="$(div2).slideToggle(500, function() { getVis(div2) })">button 2</button>
<div id = "div2">div 2 text</div>
</body>
</html>
Upvotes: 1