Reputation: 444
I'm using jQuery to open and close a hamburger menu. The class 'no-colour' and 'colour' add or remove a background.
Currently when this runs the background fills suddenly as the class is toggling. I would like it to fade in/out. I've tried 'fadeTo' and 'animate' but I couldn't get them to work as needed.
How to toggle background-color opacity of a div using jQuery?
$( '#navButton' ).click(function() {
$( '.navigation' ).slideToggle( 'slow', function() {
$( '.no-colour' ).toggleClass( 'colour' );
$( '.fa-bars' ).toggleClass( 'fa-times' );
// the above is not needed for this example it just swaps the menu icon with a 'x'
});
});
CSS:
.colour {
background-color: rgba(250, 250, 250, 1);
}
.no-colour {
background-color: rgba(250, 250, 250, 0.1);
}
Upvotes: 1
Views: 465
Reputation: 2024
Just add a css transition
and it will fade in and out for you. Watch it work in the below code snippet.
$( '#navButton' ).click(function() {
$( '.navigation' ).toggleClass('colour').toggleClass('no-colour')
});
.colour {
background-color: rgba(250, 250, 250, 1);
transition: 2s;
}
.no-colour {
background-color: rgba(250, 250, 250, 0.1);
transition: 2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="navButton">PRESS</div>
<div class="navigation no-colour">LKJSDFLSDF</div>
Upvotes: 2
Reputation: 2187
Yup, transitions should do it:
.no-colour {
background-color: rgba(250, 250, 250, 0.1);
-webkit-transition: background-color 0.7s ease-out;
-moz-transition: background-color 0.7s ease-out;
-ms-transition: background-color 0.7s ease-out;
-o-transition: background-color 0.7s ease-out;
transition: background-color 0.7s ease-out;
}
.colour {
background-color: rgba(250, 250, 250, 1);
}
Upvotes: -1