JavaScript
Article
By Sam Deering

Attempt at Animating Colour Transitions using jQuery

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

I have mentioned the .setInterval() function before. I used this function while creating a script which would (in theory) animates colour transition using jQuery. For example, go from white to light red to red to dark red such as a opacity transition would.

--ADVERTISEMENT--

Initial Attempt at Animating Colour Transition

Here is my attempt. Note that the initial results were not very good so I didn’t waste anymore time coding it but posted here mainly for my reference.

$('#input-page-url').css('border-color','rgb(255, 255, 255)');

var r = 0, g = 0, b = 0;
var interval = 25;
var borderWidth = 0;

var animateLoop  = setInterval(function() {

/* exit loop if out of colour range */
if ((r+interval) > 255) { r = 255; clearInterval(animateLoop); }
else { i++; r += interval; borderWidth += 0.2; }

$('#input-page-url').css(
      { 
         'border-color': 'rgb('+r+','+g+','+b+')',
         'border-width': borderWidth
      });


console.log('rgb('+r+','+g+','+b+')');

}, 100);

It’s a kind of .setinterval() loop example that uses the jQuery function .clearInterval() (clear setinterval) to reset the colour when it reaches 255 RGB. It then uses .CSS() to change the RGB colour of the element border.

This is also a cool plugin which does something similar: Highlight Fade which created a highlight background color fade for events.

Common error: ReferenceError: rgb is not defined

This occurs because you need to enclose the rgb in quotes (remember rgb is valid css! no need to convert to hex).

$('#input-page-url').css('border-color','rgb(redShade, 0, 0)');
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?