jQuery addClass example

Change class name on click in jQuery

by aholdorf

HTML

<div id="buttonDiv">
  <input type="button" id="randomizeButton" value="Flip"/>
  <input type="button" id="clearButton" value="Clear Tails"/>
  <input type="button" id="resetButton" value="Reset" />
</div>
<div id="pennies">
</div>

CSS

body {
}
.penny{
  width: 46px;
  height: 46px;
  z-index: 1;
  position: absolute;
}
div.h{
  background-image: url('https://wp.lps.org/aholdor/files/2020/03/Penny-PNG-Transparent-Image.png');
  background-repeat: no-repeat;
  background-size: 92px 47px;
  background-position: 1px -1px;
}
div.t, div.x{
  background-image: url('https://wp.lps.org/aholdor/files/2020/03/Penny-PNG-Transparent-Image.png');
  background-repeat: no-repeat;
  background-size: 92px 47px;
  background-position: -45px -1px;
}

JavaScript

var timer;
var c;
var ind = 0;
$(document).ready(function(){
$("#resetButton").click();
});
$("#resetButton").click(function(){
$("#pennies").html("");
ind = 0;
for(var i=0;i<100;i++){
$("#pennies").append("<div class='penny' id='cell" + i + "'>");
}
});
$("#randomizeButton").click(function(){
	var xs = [];
  var ys = [];
  for(var i=0;i<100;i++){
  	xs.push((Math.random()*200+10)/100.0);
    ys.push((Math.random()*200+100)/100.0);
  }
  for(var i=0;i<100;i++){
    	var thisCell = $("#cell" + i);

      if(!thisCell.hasClass("x")){
        thisCell.removeClass("h");
        thisCell.removeClass("t");
        if(Math.random() < 0.5){
          thisCell.addClass("h");
        }else{
          thisCell.addClass("t");
        }
      }
    }
  c = 0;
  
  timer = setInterval(function (){
  	for(var i=0;i<100;i++){
    	var thisCell = $("#cell" + i);
      if(!thisCell.hasClass("x")){
        thisCell.css("left",xs[i]*c);
        thisCell.css("top",ys[i]*c);
      }
    }
    c++;
    if(c == 100){
    	clearInterval(timer);
    }
  },2);
  
});

function moveHeads(){
	var xs = [];
  var ys = [];
  var zs = [];
  var inds = [];
  var xInd = 0;
  $(".h").each(function(){
    inds.push($(this).attr("id"));
    ys.push(((40+Math.floor(xInd/5)*30)-$(this).position().top)/10.0);
    xs.push(((10+(xInd%5)*30)-$(this).position().left)/10.0);
    zs.push(xInd);
    xInd++;
  });
   var count = 0;
   var clearTimer = setInterval(function(){
    for(var i=0;i<inds.length;i++){
    	var thisCell = $("#" + inds[i]);
        thisCell.css("left", thisCell.position().left + xs[i]);
        thisCell.css("top", thisCell.position().top + ys[i]);
        thisCell.css("z-index",zs[i]);
    }
    
    count++;
    if(count >= 10){
    clearInterval(clearTimer);
    }
   },1);
}
function moveTails(){
var xs = [];
  var ys = [];
  var zs = [];
  var inds = [];
  $(".t").each(function(){
    inds.push($(this).attr("id"));
   ...