Search code examples
jquerycsstoggleclass

jquery toggleClass no result


I have a menu which slide toggles in and out on click, but at the same time i'd like to have a grey background around the menu to fade toggle in and out. I don't want to do it with fadeToggle but with toggleClass, in order to be able to add more styles if necessary.

The toggleClass doesn't work at all, I can't figure out why. Thanks a lot for your help!!

$(document).ready(function(e) {
    $('#button').click(function() {
		$('#menu').slideToggle();
		$('#bgr').toggleClass('display');
	});
});
#menu {
    display:none;
    position: absolute; 
    top:40px; 
    right: 10%;
    z-index:10; 
    width: 30%; 
    height:400px;
    background: lightblue;}
#bgr {
    display:none;
    opacity:0;
    position:absolute; 
    top:0; 
    left:0; 
    z-index:1;
    height: 100%;
    width:100%;
    background: grey;
    -webkit-transition:opacity 1s;
    transition:opacity 1s;
}
#button {cursor: pointer;}
#button p 
{   position: absolute;
    top:0;
    right:10%;
    z-index:100;
    margin:0;
    color:lightblue;
    font-size:2em;
}
.display {
    display:block; 
    opacity:1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<div id="button">
 <p>menu</p>
</div>

<div id="menu"></div>
<div id="bgr"></div>


Solution

  • The key is using visibility and opacity in tandem for a smooth animation and also being more specific in the display declaration using #bgr.display{} instead

    http://jsfiddle.net/cceg9Ldp/4/

    CSS

    button {
        position:relative;
        z-index:2;
    }
    
    #bgr {
        opacity:0;
        visibility:hidden;
        position:absolute; 
        top:0; 
        left:0; 
        z-index:1;
        height: 100%;
        width:100%;
        background: grey;
        -webkit-transition:all 1s;
        transition:all 1s;
    }
    
     #bgr.display {
        opacity:1;
        visibility:visible;
    }
    

    HTML

    <button>Click Me</button>
    <div id="bgr"></div>
    

    jQuery

    $('button').click(function(){
        $('#bgr').toggleClass('display');
    });