Dan Brookwell
Dan Brookwell

Reputation: 341

Random blink speed across multiple DIVs

I have the following working where any DIV that has an ID of 'blink' will blink at the specified speed, all in unison. Is there a way to have each element flash at a random rate within a certain speed parameter?

jQuery(document).ready(function() {
  blink("div #blink", -1, 400);

  function blink(elem, times, speed) {
    if (times > 0 || times < 0) {
      if ($(elem).hasClass("blink"))
        $(elem).removeClass("blink");
      else
        $(elem).addClass("blink");
    }

    clearTimeout(function() {
      blink(elem, times, speed);
    });

    if (times > 0 || times < 0) {
      setTimeout(function() {
        blink(elem, times, speed);
      }, speed);
      times -= .5;
    }
  }
});
.blink {
  background: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="blink" style="background-color: blue">Example 1</div>
<div id="blink" style="background-color: blue">Example 2</div>
<div id="blink" style="background-color: blue">Example 3</div>

Upvotes: 2

Views: 161

Answers (1)

Dhiraz Gazurel
Dhiraz Gazurel

Reputation: 104

You can try giving each div a more specific id reference to your div elements and run a loop on your blink function:

jQuery(document).ready(function() {
  for(i = 1; i <= 3; i++) {
    blink("#blink-"+i, -1, i*300);
  }
  function blink(elem, times, speed) {
    if (times > 0 || times < 0) {
      if ($(elem).hasClass("blink"))
        $(elem).removeClass("blink");
      else
        $(elem).addClass("blink");
    }

    clearTimeout(function() {
      blink(elem, times, speed);
    });

    if (times > 0 || times < 0) {
      setTimeout(function() {
        blink(elem, times, speed);
      }, speed);
      times -= .5;
    }
  }
});
.blink {
  background: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="blink-1" style="background-color: blue">Example 1</div>
<div id="blink-2" style="background-color: blue">Example 2</div>
<div id="blink-3" style="background-color: blue">Example 3</div>

Upvotes: 1

Related Questions