Howard Pinsley
Howard Pinsley

Reputation: 11468

How do you make an element "flash" in jQuery

I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element — ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?

Upvotes: 279

Views: 452811

Answers (30)

Y W
Y W

Reputation: 23

You can simply use the opacity attribute like this:

.animate({opacity:0}, 1)
.animate({opacity:1})

Upvotes: 0

teknopaul
teknopaul

Reputation: 6762

CSS supports flashing in all major browsers

.flash {
    animation: flash 0.5s ease-out;
    animation-iteration-count: 10;
}
@keyframes flash {
    0% { opacity: 0.5; }
    50% { opacity: 1.0; }
    100% { opacity: 0.5; }
}

add this class to the element you want to flash

$(elem).addClass("flash");

iteration-count: 10 is how many times you want it to flash, no need to remove the class, it will stop flashing on its own.

by using opacity: this works for elements of any colour as long as its not already transparent.

Upvotes: 0

etlds
etlds

Reputation: 5890

My way is .fadein, .fadeout .fadein, .fadeout ......

$("#someElement").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

function go1() { $("#demo1").fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100)}

function go2() { $('#demo2').delay(100).fadeOut().fadeIn('slow') }
#demo1,
#demo2 {
  text-align: center;
  font-family: Helvetica;
  background: IndianRed;
  height: 50px;
  line-height: 50px;
  width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="go1()">Click Me</button>
<div id='demo1'>My Element</div>
<br>
<button onclick="go2()">Click Me</button> (from comment)
<div id='demo2'>My Element</div>

Upvotes: 391

R.Akhlaghi
R.Akhlaghi

Reputation: 760

you can use this code :) change mili value for change animation speed

var mili = 300
for (var i = 2; i < 8; i++) {
   if (i % 2 == 0) {
      $("#lblTransferCount").fadeOut(mili)
   } else {
      $("#lblTransferCount").fadeIn(mili)
   }
}

Upvotes: 0

Chris
Chris

Reputation: 788

Straight jquery, no plugins. It blinks the specified number of times, changes the background color while blinking and then changes it back.

function blink(target, count, blinkspeed, bc) {
    let promises=[];
    const b=target.css(`background-color`);
    target.css(`background-color`, bc||b);
    for (i=1; i<count; i++) {
            const blink = target.fadeTo(blinkspeed||100, .3).fadeTo(blinkspeed||100, 1.0);
            promises.push(blink);
    }
    // wait for all the blinking to finish before changing the background color back
    $.when.apply(null, promises).done(function() {
            target.css(`background-color`, b);
    });
    promises=undefined;
}

Example:

blink($(`.alert-danger`), 5, 200, `yellow`);

Upvotes: 0

Majal
Majal

Reputation: 1741

After 5 years... (And no additional plugin needed)

This one "pulses" it to the color you want (e.g. white) by putting a div background color behind it, and then fading the object out and in again.

HTML object (e.g. button):

<div style="background: #fff;">
  <input type="submit" class="element" value="Whatever" />
</div>

jQuery (vanilla, no other plugins):

$('.element').fadeTo(100, 0.3, function() { $(this).fadeTo(500, 1.0); });

element - class name

first number in fadeTo() - milliseconds for the transition

second number in fadeTo() - opacity of the object after fade/unfade

You may check this out in the lower right corner of this webpage: https://single.majlovesreg.one/v1/

Edit (willsteel) no duplicated selector by using $(this) and tweaked values to acutally perform a flash (as the OP requested).

Upvotes: 85

yPhil
yPhil

Reputation: 8357

function pulse() {
    $('.blink').fadeIn(300).fadeOut(500);
}
setInterval(pulse, 1000);

Upvotes: 7

vinay
vinay

Reputation: 2984

You can use css3 animations to flash an element

.flash {
  -moz-animation: flash 1s ease-out;
  -moz-animation-iteration-count: 1;

  -webkit-animation: flash 1s ease-out;
  -webkit-animation-iteration-count: 1;

  -ms-animation: flash 1s ease-out;
  -ms-animation-iteration-count: 1;
}

@keyframes flash {
    0% { background-color: transparent; }
    50% { background-color: #fbf8b2; }
    100% { background-color: transparent; }
}

@-webkit-keyframes flash {
    0% { background-color: transparent; }
    50% { background-color: #fbf8b2; }
    100% { background-color: transparent; }
}

@-moz-keyframes flash {
    0% { background-color: transparent; }
    50% { background-color: #fbf8b2; }
    100% { background-color: transparent; }
}

@-ms-keyframes flash {
    0% { background-color: transparent; }
    50% { background-color: #fbf8b2; }
    100% { background-color: transparent; }
}

And you jQuery to add the class

jQuery(selector).addClass("flash");

Upvotes: 109

Michiel Overeem
Michiel Overeem

Reputation: 3982

You could use the highlight effect in jQuery UI to achieve the same, I guess.

Upvotes: 47

Iman
Iman

Reputation: 18896

you can use jquery Pulsate plugin to force to focus the attention on any html element with control over speed and repeatation and color.

JQuery.pulsate() * with Demos

sample initializer:

  • $(".pulse4").pulsate({speed:2500})
  • $(".CommandBox button:visible").pulsate({ color: "#f00", speed: 200, reach: 85, repeat: 15 })

Upvotes: 1

Combine
Combine

Reputation: 4214

$("#someElement").fadeTo(3000, 0.3 ).fadeTo(3000, 1).fadeTo(3000, 0.3 ).fadeTo(3000, 1); 

3000 is 3 seconds

From opacity 1 it is faded to 0.3, then to 1 and so on.

You can stack more of these.

Only jQuery is needed. :)

Upvotes: 3

curthipster
curthipster

Reputation: 3671

You can use the jQuery Color plugin.

For example, to draw attention to all the divs on your page, you could use the following code:

$("div").stop().css("background-color", "#FFFF9C")
    .animate({ backgroundColor: "#FFFFFF"}, 1500);

Edit - New and improved

The following uses the same technique as above, but it has the added benefits of:

  • parameterized highlight color and duration
  • retaining original background color, instead of assuming that it is white
  • being an extension of jQuery, so you can use it on any object

Extend the jQuery Object:

var notLocked = true;
$.fn.animateHighlight = function(highlightColor, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = duration || 1500;
    var originalBg = this.css("backgroundColor");
    if (notLocked) {
        notLocked = false;
        this.stop().css("background-color", highlightBg)
            .animate({backgroundColor: originalBg}, animateMs);
        setTimeout( function() { notLocked = true; }, animateMs);
    }
};

Usage example:

$("div").animateHighlight("#dd0000", 1000);

Upvotes: 127

Roman Losev
Roman Losev

Reputation: 1941

Like fadein / fadeout you could use animate css / delay

$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);

Simple and flexible

Upvotes: 3

SooDesuNe
SooDesuNe

Reputation: 10030

If you're using jQueryUI, there is pulsate function in UI/Effects

$("div").click(function () {
      $(this).effect("pulsate", { times:3 }, 2000);
});

http://docs.jquery.com/UI/Effects/Pulsate

Upvotes: 47

hakunin
hakunin

Reputation: 4231

Pure jQuery solution.

(no jquery-ui/animate/color needed.)

If all you want is that yellow "flash" effect without loading jquery color:

var flash = function(elements) {
  var opacity = 100;
  var color = "255, 255, 20" // has to be in this format since we use rgba
  var interval = setInterval(function() {
    opacity -= 3;
    if (opacity <= 0) clearInterval(interval);
    $(elements).css({background: "rgba("+color+", "+opacity/100+")"});
  }, 30)
};

Above script simply does 1s yellow fadeout, perfect for letting the user know the element was was updated or something similar.

Usage:

flash($('#your-element'))

Upvotes: 16

NateS
NateS

Reputation: 5876

This is generic enough that you can write whatever code you like to animate. You can even decrease the delay from 300ms to 33ms and fade colors, etc.

// Flash linked to hash.
var hash = location.hash.substr(1);
if (hash) {
    hash = $("#" + hash);
    var color = hash.css("color"), count = 1;
    function hashFade () {
        if (++count < 7) setTimeout(hashFade, 300);
        hash.css("color", count % 2 ? color : "red");
    }
    hashFade();
}

Upvotes: 1

Nizar B.
Nizar B.

Reputation: 3118

You can use this cool library to make any kind of animated effect on your element: http://daneden.github.io/animate.css/

Upvotes: -1

maudulus
maudulus

Reputation: 11025

Create two classes, giving each a background color:

.flash{
 background: yellow;
}

.noflash{
 background: white;
}

Create a div with one of these classes:

<div class="noflash"></div>

The following function will toggle the classes and make it appear to be flashing:

var i = 0, howManyTimes = 7;
function flashingDiv() {
    $('.flash').toggleClass("noFlash")
    i++;
    if( i <= howManyTimes ){
        setTimeout( f, 200 );
    }
}
f();

Upvotes: 0

ibsenv
ibsenv

Reputation: 619

just give elem.fadeOut(10).fadeIn(10);

Upvotes: 1

shanehoban
shanehoban

Reputation: 870

Working with jQuery 1.10.2, this pulses a dropdown twice and changes the text to an error. It also stores the values for the changed attributes to reinstate them.

// shows the user an error has occurred
$("#myDropdown").fadeOut(700, function(){
    var text = $(this).find("option:selected").text();
    var background = $(this).css( "background" );

    $(this).css('background', 'red');
    $(this).find("option:selected").text("Error Occurred");

        $(this).fadeIn(700, function(){
            $(this).fadeOut(700, function(){
                $(this).fadeIn(700, function(){
                    $(this).fadeOut(700, function(){

                        $(this).find("option:selected").text(text);
                        $(this).css("background", background);
                        $(this).fadeIn(700);
                    })
                })
            })
        })
});

Done via callbacks - to ensure no animations are missed.

Upvotes: 0

sffc
sffc

Reputation: 6414

Here's a solution that uses a mix of jQuery and CSS3 animations.

http://jsfiddle.net/padfv0u9/2/

Essentially you start by changing the color to your "flash" color, and then use a CSS3 animation to let the color fade out. You need to change the transition duration in order for the initial "flash" to be faster than the fade.

$(element).removeClass("transition-duration-medium");
$(element).addClass("transition-duration-instant");
$(element).addClass("ko-flash");
setTimeout(function () {
    $(element).removeClass("transition-duration-instant");
    $(element).addClass("transition-duration-medium");
    $(element).removeClass("ko-flash");
}, 500);

Where the CSS classes are as follows.

.ko-flash {
    background-color: yellow;
}
.transition-duration-instant {
    -webkit-transition-duration: 0s;
    -moz-transition-duration: 0s;
    -o-transition-duration: 0s;
    transition-duration: 0s;
}
.transition-duration-medium {
    -webkit-transition-duration: 1s;
    -moz-transition-duration: 1s;
    -o-transition-duration: 1s;
    transition-duration: 1s;
}

Upvotes: 1

Xanarus
Xanarus

Reputation: 775

Simple as the best is to do in this way :

<script>

setInterval(function(){

    $(".flash-it").toggleClass("hide");

},700)
</script>

Upvotes: 0

Rob Evans
Rob Evans

Reputation: 6968

You can extend Desheng Li's method further by allowing an iterations count to do multiple flashes like so:

// Extend jquery with flashing for elements
$.fn.flash = function(duration, iterations) {
    duration = duration || 1000; // Default to 1 second
    iterations = iterations || 1; // Default to 1 iteration
    var iterationDuration = Math.floor(duration / iterations);

    for (var i = 0; i < iterations; i++) {
        this.fadeOut(iterationDuration).fadeIn(iterationDuration);
    }
    return this;
}

Then you can call the method with a time and number of flashes:

$("#someElementId").flash(1000, 4); // Flash 4 times over a period of 1 second

Upvotes: 12

Duncan
Duncan

Reputation: 11

Put this together from all of the above - an easy solution for flashing an element and return to the original bgcolour...

$.fn.flash = function (highlightColor, duration, iterations) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = duration || 1500;
    var originalBg = this.css('backgroundColor');
    var flashString = 'this';
    for (var i = 0; i < iterations; i++) {
        flashString = flashString + '.animate({ backgroundColor: highlightBg }, animateMs).animate({ backgroundColor: originalBg }, animateMs)';
    }
    eval(flashString);
}

Use like this:

$('<some element>').flash('#ffffc0', 1000, 3);

Hope this helps!

Upvotes: 1

Chloe
Chloe

Reputation: 26264

Unfortunately the top answer requires JQuery UI. http://api.jquery.com/animate/

Here is a vanilla JQuery solution

http://jsfiddle.net/EfKBg/

JS

var flash = "<div class='flash'></div>";
$(".hello").prepend(flash);
$('.flash').show().fadeOut('slow');

CSS

.flash {
    background-color: yellow;
    display: none;
    position: absolute;
    width: 100%;
    height: 100%;
}

HTML

<div class="hello">Hello World!</div>

Upvotes: 2

Brad
Brad

Reputation: 321

This one will pulsate an element's background color until a mouseover event is triggered

$.fn.pulseNotify = function(color, duration) {

var This = $(this);
console.log(This);

var pulseColor = color || "#337";
var pulseTime = duration || 3000;
var origBg = This.css("background-color");
var stop = false;

This.bind('mouseover.flashPulse', function() {
    stop = true;
    This.stop();
    This.unbind('mouseover.flashPulse');
    This.css('background-color', origBg);
})

function loop() {
    console.log(This);
    if( !stop ) {
        This.animate({backgroundColor: pulseColor}, pulseTime/3, function(){
            This.animate({backgroundColor: origBg}, (pulseTime/3)*2, 'easeInCirc', loop);
        });
    }
}

loop();

return This;
}

Upvotes: 1

TonyP
TonyP

Reputation: 91

How about a really simple answer?

$('selector').fadeTo('fast',0).fadeTo('fast',1).fadeTo('fast',0).fadeTo('fast',1)

Blinks twice...that's all folks!

Upvotes: 8

SoEzPz
SoEzPz

Reputation: 15912

I was looking for a solution to this problem but without relying on jQuery UI.

This is what I came up with and it works for me (no plugins, just Javascript and jQuery); -- Heres the working fiddle -- http://jsfiddle.net/CriddleCraddle/yYcaY/2/

Set the current CSS parameter in your CSS file as normal css, and create a new class that just handles the parameter to change i.e. background-color, and set it to '!important' to override the default behavior. like this...

.button_flash {
background-color: #8DABFF !important;
}//This is the color to change to.  

Then just use the function below and pass in the DOM element as a string, an integer for the number of times you would want the flash to occur, the class you want to change to, and an integer for delay.

Note: If you pass in an even number for the 'times' variable, you will end up with the class you started with, and if you pass an odd number you will end up with the toggled class. Both are useful for different things. I use the 'i' to change the delay time, or they would all fire at the same time and the effect would be lost.

function flashIt(element, times, klass, delay){
  for (var i=0; i < times; i++){
    setTimeout(function(){
      $(element).toggleClass(klass);
    }, delay + (300 * i));
  };
};

//Then run the following code with either another delay to delay the original start, or
// without another delay.  I have provided both options below.

//without a start delay just call
flashIt('.info_status button', 10, 'button_flash', 500)

//with a start delay just call
setTimeout(function(){
  flashIt('.info_status button', 10, 'button_flash', 500)
}, 4700);
// Just change the 4700 above to your liking for the start delay.  In this case, 
//I need about five seconds before the flash started.  

Upvotes: 6

Cau&#234;h Q.
Cau&#234;h Q.

Reputation: 114

This function makes it blink. It must use cssHooks, because of the rgb default return of background-color function.

Hope it helps!

$.cssHooks.backgroundColor = {
get: function(elem) {
    if (elem.currentStyle)
        var bg = elem.currentStyle["backgroundColor"];
    else if (window.getComputedStyle)
        var bg = document.defaultView.getComputedStyle(elem,
            null).getPropertyValue("background-color");
    if (bg.search("rgb") == -1)
        return bg;
    else {
        bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
    }
}
}
function blink(element,blinkTimes,color,originalColor){
    var changeToColor;
    if(blinkTimes === null || blinkTimes === undefined)
        blinkTimes = 1;
    if(!originalColor || originalColor === null || originalColor === undefined)
        originalColor = $(element).css("backgroundColor");
    if(!color || color === null || color === undefined)
        color = "#ffffdf";
    if($(element).css("backgroundColor") == color){
        changeToColor = originalColor;
    }else{
        changeToColor = color;
        --blinkTimes;
    }
    if(blinkTimes >= 0){
        $(element).animate({
            "background-color": changeToColor,
        }, {
            duration: 500,
            complete: function() {
                blink(element, blinkTimes, color, originalColor);
                return true;
            }
        });
    }else{
        $(element).removeAttr("style");
    }
    return true;
}

Upvotes: 0

phillyd
phillyd

Reputation: 51

Found this many moons later but if anyone cares, it seems like this is a nice way to get something to flash permanently:

$( "#someDiv" ).hide();

setInterval(function(){
     $( "#someDiv" ).fadeIn(1000).fadeOut(1000);
},0)

Upvotes: 5

Related Questions