Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript background color blink with fade

I have a div that needs to have a constant flashing background color.

All I want it to do is fade in from transparent to red and back in a loop. I've seen a few examples that do this, but they all affect the entire contents of the div rather than just the background color.

Other examples have a flashing background but it's not a smooth transition, which is what I need.

I'd rather not use CSS animations if possible.

Thanks for any help!

like image 396
Ryan McClure Avatar asked Feb 03 '26 05:02

Ryan McClure


1 Answers

You can use rgba color to fade the color to transparent.

Example:

var ofs = 0;
var el = document.getElementById('imp');

window.setInterval(function(){
  el.style.background = 'rgba(255,0,0,'+Math.abs(Math.sin(ofs))+')';
  ofs += 0.01;
}, 10);

Demo: http://jsfiddle.net/Guffa/BUL2z/

Using jQuery:

var ofs = 0;

window.setInterval(function(){
  $('#imp').css('background', 'rgba(255,0,0,'+Math.abs(Math.sin(ofs))+')');
  ofs += 0.01;
}, 10);
like image 161
Guffa Avatar answered Feb 04 '26 19:02

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!