Question

http://jsfiddle.net/vmKVS/

I am trying to understand the state of slideToggle with a little example.

When I toggle the first time the options element turns green.

I would expect the menu element to turn red when I click toggle again, now the 2nd time, since now the options element goes into not visible state and therefore the else part of the function should run, no?

Also when I check the console the values for the slideToggle state do not change, why? Should they not reflect the state of the element after the click second click, so hidden?

What am I doing wrong? I would like to have for the sake of this example, turn the menu red on the second toggle, since then the options element is not visible any more.

I am new to jQuery and programming, so please forgive my blatant mistakes in logic here. Perhaps I have to rethink this from a different viewpoint. This is where you come in, help me understand this please. Thank you.

HTML

<div id="menu">MENU</div>
<div id="options">OPTIONS</div>

jQuery

$('#menu').click(function(){

    $('#options').slideToggle();

    var isVisible = $( '#options' ).is( ":visible" );
    var isHidden = $( '#options' ).is( ":hidden" );
    console.log (isVisible);
    console.log (isHidden);

    if ($('#options').is(':visible') === true ){
        $('#options').css('background', '#16a085');
        console.log (isVisible);
    }

    else {
        console.log (isHidden);
        $('#menu').css('background', '#8e44ad');        
    }    
});

CSS

#menu {
    width: 100%;
    height: 100px;
    line-height: 100px;
    font-size: 200%;
    background: #000000;
    color: #fff;
    text-align: center;
}

#options {
    width: 100%;
    height: 100px;
    line-height: 100px;
    font-size: 200%;
    background: #ccc;
    color: #fff;
    text-align: center;
    display: none;
}
Was it helpful?

Solution

Check out the documentation for the jQuery :visible and :hidden selectors more thoroughly:

http://api.jquery.com/visible-selector/

http://api.jquery.com/hidden-selector/

The issue is that the :visible selector will return true if the element that is selected consumes space within the layout, and as the width is not zero, this is true.

There are plenty of ways to do what you're after. A nice way is to toggle a class and use that to detect whether the item is toggled:

$('#menu').click(function(){

    $('#options').slideToggle().toggleClass('opened');

    var isVisible = $( '#options' ).is( ".opened" );

    if (isVisible === true ){
        $('#options').css('background', '#16a085');
    }

    else {
        $('#menu').css('background', '#8e44ad');        
    }    
});

http://jsfiddle.net/vmKVS/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top