John.A.
John.A.

Reputation: 1

jquery css function doesn't work for detecting element shown/hidden

My code:

<script type="text/javascript">
    $(function(){
        $("body").click(function(){
            $("ul").toggle("slow");
            var b = $("ul").css("display");
            console.log("ul display :"+b);// unfortunately,always returns block!
    });
});
</script>
</head>
<body>
    <nav>
        <ul>
            <li><a href="/">home</a></li>
            <li><a href="/archive/">Archive</a></li>
            <li><a href="/about/">About</a></li>
            <li><a href="/contact/">Contact</a></li>
        </ul>
    </nav>
</body>
</html>

I use jquery toggle() function to show/hide. But toggle() doesn't change css value, so you can't use .css("display") function to check the state of display.Even elements are hidden, .css("display") always returns "block", if your original css sheet defines "display:block;".

How do you detect display state which meens that if the element is shown or hidden? Or, do you know the way to change real display value which toggle() couldn't achieve?

note: you can't use the way shown below, because the previous code is test code and in real codes, toggle() and .css("display") are in different functions and excuted in completely different timing.

$("ul").toggle("slow", function() {
  ...
}

Upvotes: 0

Views: 889

Answers (2)

lashab
lashab

Reputation: 186

$(function(){
  $("body").click(function(){
     $("ul").toggle("slow",function(){
         console.log($(this).css('display')); //none
      });
    });
});

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

I think the main problem here is that the code is not waiting for the animation to complete when checking the state so it is actually still visible when it runs.

If you check the state after the animation is completed (in the callback function) it correctly returns none:

$("body").click(function(){
    $("ul").toggle("slow", function() {
        var b = $("ul").css("display");
        console.log("ul display :"+b); // This will return none
    });
    var b = $("ul").css("display");
    console.log("ul display :"+b); // This will return block
});

This example will display block immediately then none after hiding the element - http://jsfiddle.net/Vw9nA/

But as stated in the comments and the other linked question, the best way to check visibility is $('ul').is(':visible')

Upvotes: 2

Related Questions