Brandrally
Brandrally

Reputation: 851

jQuery - Placing a 1 second transition on a CSS background color toggle

The code I have works as intended, except I cannot manage to put a 1 second transition on the CSS color change.

The background changes color. Just with no transition. I have been staring at this forever and trying subtle changes and I cannot seem to get it to work. Any help would be greatly appreciated.

Javascript:

$(window).load(function(){

var navPos = 1,
init = true;

$(window).scroll(function () {
    var fixIT = $(this).scrollTop() >= navPos;
    var setPos = fixIT ? 'fixed' : 'relative';
    var setBG = fixIT ? '#000' : '#1db8af';
    $('#navigation').css({  position: setPos });
    $('#navigation').css({  background: setBG}, {transition : 'opacity 1s ease-in-out'});
});
});

Upvotes: 1

Views: 197

Answers (1)

Nisarg Shah
Nisarg Shah

Reputation: 14531

I suppose the core issue here is that the transition property in your snippet is "opacity". You need to change that to "background-color" (or "background" or "all").

Also, for transition to work, it has to be set before the property value changes. So you could move the "transition" property declaration to a separate CSS rule.

$(() => $('#navigation').css({
  background: "red"
}));
#navigation {
  background-color: yellow;
  transition: background-color 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="navigation">
  Test
</div>

Upvotes: 5

Related Questions