Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Opacity Fade In Out Loop

One of my clients asked me to make a blinking effect on a div. I think that might not be the best thing for him, maybe light fading in and out of opacity will get the attention of his customers, without annoying them.

I currently have

 <a class="special_button" href="#">Special Offers &rsaquo;</a>

I have the following code for another div, which causes a fade in on browser load :

$('.logo-top').delay(700).animate({
     'opacity' : '1',        
     'top' : '+=40px'
}, { duration: 700, easing: 'swing' });

How would I do something similar for the special_button, but instead looping the opacity? From say 80 to 100?

It would even be better if it looped a certain amount of times, maybe like 5.

Best, Stepan

like image 389
Stepan Parunashvili Avatar asked Oct 05 '12 05:10

Stepan Parunashvili


3 Answers

You probably want to have something like this jsFiddle.

And you can also indicate the number of times you want this to blink, just by keeping a counter.

Code from jsFiddle:

$(document).ready(function() {
     function runIt() {           
       var baloon = $('#baloon');
       baloon.animate({opacity:'1'}, 1000);
       baloon.animate({opacity:'0.5'}, 1000, runIt);
    }
    runIt();
});
like image 146
Ulan Murzatayev Avatar answered Oct 05 '22 02:10

Ulan Murzatayev


Why not use CSS3 keyframes?

.twinkle {
  background: red;
  padding: 0.2em;
  margin: 50px;
}

@-webkit-keyframes twinkly {
  from {opacity: 1;}
  to {opacity: 0.4;}
}

@-moz-keyframes twinkly {
  from {opacity: 1;}
  to {opacity: 0.4;}
}

@-ms-keyframes twinkly {
  from {opacity: 1;}
  to {opacity: 0.4;}
}

@keyframes twinkly {
  from {opacity: 1;}
  to {opacity: 0.4;}
}

.twinkle {
  -webkit-animation: twinkly 1s alternate infinite;
  -moz-animation: twinkly 1s alternate infinite;
  -ms-animation: twinkly 1s alternate infinite;
  animation: twinkly 1s alternate infinite;
}
<span class="twinkle">Special Offers &rsaquo;</span>

You can use a fallback for older browsers then. Any of the scripts the other propsed are good but I would advise Ulan's solution.

like image 29
Bram Vanroy Avatar answered Oct 05 '22 01:10

Bram Vanroy


You can do it like this;

(function() {
    var cnt = 0;
    var specials = $(".special_button");

    function next() {
        if (cnt < 5) {
            specials.fadeTo(2000, .1).fadeTo(2000, 1, next);
            ++cnt;
        }                    
    }

    next();
})();
​

Working demo: http://jsfiddle.net/jfriend00/558GY/

FYI, the difference between 80% and 100% opacity is pretty subtle. I made the difference much greater in the demo. You can obviously tune to whatever effect you want.

like image 37
jfriend00 Avatar answered Oct 05 '22 00:10

jfriend00