Brock Whittaker
Brock Whittaker

Reputation: 71

How could I en mass change divs in jquery randomly?

Here's a jsfiddle:

http://jsfiddle.net/zyqqLtk4/

Basically I have one div that twinkles because when a random number is generated, opacity is set as < 0.5 then -> 0, else = 1.0. How could I use the following:

var opacity = 0;
var myVar = setInterval(function () {
    opacity = Math.random();
    if (opacity > 0.5) {
        opacity = 1;
    } else {
        opacity = 0;
    }
    $('.point1').css('opacity', opacity);

}, 50);

But on a hundred divs for instance with each being a completely different random value (meaning they aren't tied together by the same binary opacity).

Thanks!

Upvotes: 0

Views: 109

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use .each() to iterate through a set of elements like

$('.point').each(function() {
  var $this = $(this);
  var myVar = setInterval(function() {
    $this.css('opacity', Math.round(Math.random()));

  }, 50);
})
@import url(http://fonts.googleapis.com/css?family=Roboto+Condensed:400, 300|Roboto:400, 300, 100, 500|Dancing+Script:400, 700);
 .point {
  width: 10px;
  height: 10px;
  background-color: Black;
  border-radius: 5px;
  margin: 0px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128791

You can use jQuery's each() method to iterate through each of your .point1 elements, then apply the opacity individually to each one:

$('.point').each(function() {
    $(this).css({ opacity: Math.random() > 0.5 ? 1 : 0 });
});

JSFiddle demo

Code Snippet

$('.point').each(function() {
    $(this).css({ opacity: Math.random() > 0.5 ? 1 : 0 });
});
@import url(http://fonts.googleapis.com/css?family=Roboto+Condensed:400,300|Roboto:400,300,100,500|Dancing+Script:400,700);
.point {
    width: 10px;
    height: 10px;
    background-color: Black;
    border-radius: 5px;
    margin: 0px;
    display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>
<div class="point"></div>

Upvotes: 3

Related Questions