Jake
Jake

Reputation: 1295

jQuery animate div background color gradient?

I'm trying to build a background animation with jQuery which changes from one gradient to another. I know you can use the .animate() function to change solid background colors, but can this also be done for gradients?

Here's a good example from some old Digg-style comments. I'm looking to do something like this animating from green to yellow

enter image description here

Upvotes: 5

Views: 25817

Answers (7)

$('#btn').on('click', function(){
    $({num: 0}).animate({num: 100}, { //Анимация от 0 до 100
        duration: 2000, // Скорость анимации
        easing: "swing",
        step: function(val) {
            $('.mark').html(Math.ceil(val)+'%');
            $('.mark').css('background', 'linear-gradient(90deg, #5ac740 '+val+'%, #b19bb8 '+val+'%)');
        }
    });
});
.markwrapper{
    width:500px;
    height:25px;
    padding-bottom: 10px;
    display: table;
}

.mark{
    color: #ffffff;
    font-weight: 600;
    background: #b19bb8;
    font-size: 12px;
    font-family: 'FuturaPT',Arial,sans-serif;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    border-radius: 50px;
    box-sizing: border-box;
}

#btn{
    color: #ffffff;
    padding: 5px 20px;
    font-weight: 600;
    background: #828282;
    font-size: 12px;
    font-family: 'FuturaPT',Arial,sans-serif;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    border-radius: 50px;
    box-sizing: border-box;
    border: 0;
    cursor:pointer;
}
<!--Подключаем библиотеку-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="markwrapper">
    <div class="mark">0%</div>
</div>
<div>
    <button id="btn">Click</button>
</div>  

Background на Jquery

Upvotes: 0

Igor Еfron
Igor Еfron

Reputation: 26

i wrote a solution with jQuery, where you can define colors and order in which they would be changed from one to another:

in the example below, the animation goes from green to purple, and then back to green, and so on, until the animation stops after defined number of seconds

var stopAfterSec = 23;
var speed = 15;

var purple = [255, 26, 26];
var green = [26, 255, 118];
var sea_green = [26, 255, 244];

var order = [green, sea_green, purple];

var current = 0;
var direction = -1;
var color = end_color = order[current];

function updateGradient() {
  if (color[0] == end_color[0] && color[1] == end_color[1] && color[2] == end_color[2]) {
    direction = (current > 0 && current < order.length - 1) ? direction : (-1) * Math.sign(direction);
    current += direction;
    end_color = order[current];
  }

  $('.animGradientEfron').css({
    background: "-webkit-radial-gradient(center, ellipse cover, rgba(0, 0, 0, 1) 0%, rgba(" + color[0] + ", " + color[1] + ", " + color[2] + ", 0.48) 100%)"
  });
  for (var i = 0; i <= 2; i++) {
    if (color[i] != end_color[i]) {
      color[i] += Math.sign((end_color[i] - color[i]));
    }
  }
}

jQuery(document).ready(function() {
  var startGradientAnimation = setInterval(updateGradient, speed);

  setTimeout(function() {
    clearInterval(startGradientAnimation);
  }, stopAfterSec * 1000);

});
.animGradientEfron {
  position: absolute;
  top: 25%;
  left: 0%;
  width: 100%;
  height: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animGradientEfron"></div>

Upvotes: 0

arik
arik

Reputation: 29250

UPDATE: These days, all major browsers support CSS animations, which are way more reliable than jQuery. For reference, see Rohit's answer.

OLD ANSWER:

Animating the backgrounds directly is nearly impossible with jQuery, at least I could think of no way. There is a way though with this:

-webkit-transition: background 5s ;
-moz-transition: background 5s ;
-ms-transition: background 5s ;
-o-transition: background 5s ;
transition: background 5s ;

That ensures that there is a transition. You could for instance do that in CSS:

.background_animation_element{

    -webkit-transition: background 5s ;
    -moz-transition: background 5s ;
    -ms-transition: background 5s ;
    -o-transition: background 5s ;
    transition: background 5s ;

    background: rgb(71,234,46);
    background: -moz-linear-gradient(top,  rgba(71,234,46,1) 0%, rgba(63,63,63,1) 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(71,234,46,1)), color-stop(100%,rgba(63,63,63,1)));
    background: -webkit-linear-gradient(top,  rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
    background: -o-linear-gradient(top,  rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
    background: -ms-linear-gradient(top,  rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
    background: linear-gradient(top,  rgba(71,234,46,1) 0%,rgba(63,63,63,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#47ea2e', endColorstr='#3f3f3f',GradientType=0 );

}

.background_animation_element.yellow{

    background: rgb(247,247,49);
    background: -moz-linear-gradient(top,  rgba(247,247,49,1) 0%, rgba(63,63,63,1) 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(247,247,49,1)), color-stop(100%,rgba(63,63,63,1)));
    background: -webkit-linear-gradient(top,  rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
    background: -o-linear-gradient(top,  rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
    background: -ms-linear-gradient(top,  rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
    background: linear-gradient(top,  rgba(247,247,49,1) 0%,rgba(63,63,63,1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f7f731', endColorstr='#3f3f3f',GradientType=0 );

}

And, using jQuery, either add or remove the yellow class:

$('.background_animation_element').addClass('yellow');

That would ensure a gradual transition due to the transition duration property in the CSS file.

Upvotes: 4

Khaled Al-Ansari
Khaled Al-Ansari

Reputation: 3970

You can try Backgroundor, it's a jquery plugin for grandient animation.

It's so simple just write $('#yourDivId').backgroundor(); and it will work! it got a lot options like change the degree of the gradient the time of the animation.

Upvotes: 0

Rohit Suthar
Rohit Suthar

Reputation: 3628

Try this, work great -

div{
     display:block; 
     width:500px; 
     height:250px;
     background: linear-gradient(270deg, #509591, #7bc446, #c0de9e, #b9dca4);
     background-size: 800% 800%;

     -webkit-animation: AnimationName 30s ease infinite;
     -moz-animation: AnimationName 30s ease infinite;
     animation: AnimationName 30s ease infinite;
}


@-webkit-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-o-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
<div></div>

source - https://www.gradient-animator.com/

Upvotes: 4

lyyons
lyyons

Reputation: 393

Animating the background with jQuery is definitely feasible, as seen in this CodePen (not my creation, but very slick): http://codepen.io/quasimondo/pen/lDdrF

The CodePen example uses some slick bitshifting and other tricks to determine the colors, but he just defines a function (updateGradient) that modifies the background's CSS and then wraps it in a setInterval.

The big takeaway from the updateGradient is the following:

 $('#gradient').css({
     background: "-webkit-gradient(linear, left top, right top, from("+color1+"),
   to("+color2+"))"}).css({
     background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

Then just set the color variables dynamically and you're gravy.

Upvotes: 6

Zulfugar Ismayilzadeh
Zulfugar Ismayilzadeh

Reputation: 2763

I needed it too, i searched it in google. But didn't find any solution, so i solve this. I do with this dirty way, but worked :) This is my code:

interval = 0;
gradient_percent = 0;
interval_value = 5;
var interval_gradient = setInterval(function(){
    if(interval == 10) clearInterval(interval_gradient);

    gradient_percent += interval_value;
    $('.slider-text').css('background', 'linear-gradient(to right, #373535 '+gradient_percent+'%,rgba(0,0,0,0) 100%)');

    ++interval;
}, 50);

Upvotes: 2

Related Questions