views:

530

answers:

3

I have two divs that I want to make blink at the same time until the user hovers the mouse on one of them.

var shouldiblink = '1';

function mrBlinko(divid){
 while (shouldiblink =='1') {
 $("#"+divid).fadeIn(100).fadeOut(300);
}

$(document).ready(function(){
 mrBlinko("mydiv1");
 mrBlinko("mydiv2");
}

The I'll have an hover event that sets shouldiblink to '0'. Problem is that the loops starts as soon as the page is ready and the browser crashes.

I'm stuck with this solution and I can't think of an alternative right now.

Can you help me?

Thank you very much.

A: 

One of the alternatives - Pulsate effect from jQuery UI.

Include it from google API in order to improve performance.


If you want to roll your own solution, you might find useful checking out source code of pulsate effect.

Arnis L.
+1  A: 

I think the better way will be to use setInterval and clearInterval.

Once the page is loaded use setInterval to get the effect going. When the user hovers the mouse over the element then clear the interval using the interval id attained for setInterval.

See a working demo.

rahul
Thank you very much, it was exactly what I was looking for.
0plus1
A: 

As much as I hated the <blink> tag, try this:

$.fn.blink = function(opts) {
   // allows $elem.blink('stop');
   if (opts == 'stop') {
     // sets 'blinkStop' on element to true, stops animations, 
     // and shows the element.  Return this for chaining.
     return this.data('blinkStop', true).stop(true, true).show();
   }

   // we aren't stopping, so lets set the blinkStop to false,
   this.data('blinkStop', false);

   // load up some default options, and allow overriding them:
   opts = $.extend({}, {
     fadeIn: 100,
     fadeOut: 300
   }, opts || {} );

   function doFadeOut($elem) {
     $elem = $elem || $(this); // so it can be called as a callback too
     if ($elem.data('blinkStop')) return;
     $elem.fadeOut(opts.fadeOut, doFadeIn);
   }
   function doFadeIn($elem) {
     $elem = $elem || $(this);
     if ($elem.data('blinkStop')) return;
     $elem.fadeIn(opts.fadeIn, doFadeOut);
   }
   doFadeOut(this);
   return this;
 };

 // example usage - blink all links until you mouseover:
 // takes advantage of the jQuery.one() function so that it only calls the 
 // stop blink once
 $('a').blink({fadeIn: 500, fadeOut: 1500}).one('mouseover', function() { 
   $(this).blink('stop') 
 });

 // 30 seconds after we started blinking, stop blinking every element we started:
 setTimeout(function() { 
   $('a').blink('stop');
 }, 30000);

 // example that should do what you wanted:
 $("#mydiv1,#mydiv2").blink().one('mouseover', function() {
   $(this).blink('stop');
 });
gnarf