2

I was reading this question about how to make an element "flash" in jQuery, however, the most popular answers relied on jQueryUI which is pretty large to include in a project if all I need is the backgroundColor to animate. Is there a way to flash an element's background color in a similar manner without using jQueryUI?

Community
  • 1
  • 1
Ivan
  • 10,052
  • 12
  • 47
  • 78
  • 3
    To accomplish this "flash" you only need ui effects core and the ui effect. jQuery UI is designed to be used in pieces for this reason, you don't need all the code for widgets if you aren't using them... – gnarf Oct 21 '11 at 18:53
  • Possible duplicate of [How do you make an element "flash" in jQuery](https://stackoverflow.com/questions/275931/how-do-you-make-an-element-flash-in-jquery) – cweiske Aug 07 '18 at 12:10

4 Answers4

2

you can write a function that contains a for loop with some delay in each cycle. In each cycle of the loop, you can decrease/increase the color value and set it as the background. This gives the same effect as that of animate.

Vivek Viswanathan
  • 1,968
  • 18
  • 26
1

Something like this should work (I hope).

function flash($element, times) {
  var colors = ['#fff', '#000'];
  $element.css('background-color', colors[times % colors.length]);
  if (times === 0) return;
  setTimeout(function () {
    flash($element, times - 1);
  }, 500);
}

Use it on an element like this: flash($('#some_element'), 5)

Community
  • 1
  • 1
Markus Hedlund
  • 23,374
  • 22
  • 80
  • 109
0

One way:

setInterval(function(){
  $('#hello').css('background-color', 'red');
}, 100);

setInterval(function(){
  $('#hello').css('background-color', 'green');
}, 150);

DEMO

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Bad way. These two intervals would easily go out of sync with each other. It would be better to use just one which toggles the effect using a boolean or such. – Clox Oct 24 '16 at 12:36
-2

After a bit of searching through the answers on that page, I found a link to a jQuery workaround that allows one to call a function .highlight() on a jQuery element. While jQuery is needed, jQueryUI is not.

Ivan
  • 10,052
  • 12
  • 47
  • 78
  • 1
    if this answers your own question you can still mark it as such. also I think jquery ui relays on "effects.js" to make that work. so if jquery didn't do it on its on you might look at effects. – Eonasdan Oct 21 '11 at 18:54