javascript - How to give each div created from setInterval an id starting from 1 -


i know question might have been answered few times, cannot seem work in code. willing thank you.

i have object creates rectangle on screen run setinerval recreate rectangle on screen in order many rectangles shown 1 after other on screen.

the problem: need give each rectangle id, don't know jquery , if implement attr on .block jquery changes id's of divs.

i want each new div created have own id example id=block1 next div id=block2 , on , of them of class block.

var cheight = window.innerheight - 150; //size of block var cwidth = window.innerwidth - 150;   var block = function(block) {     this.block = document.createelement('div');     this.block.classname = 'block';        document.body.appendchild(this.block);  }  block.prototype.coordinates = function(top,left) {     this.block.style.top =  top + 'px';     this.block.style.left = left + 'px'; }  block.prototype.size = function(width,height) {     this.block.style.width = width + 'px';     this.block.style.height = height + 'px'; }   function randomtop() {     var = math.random();     var y = (i * (cheight - 0 + 1)) +0;     var x = math.floor(y);     return x; }  function randomleft() {     var = math.random();     var y = (i * (cwidth - 0 + 1)) + 0;     var x = math.floor(y)     return x; }   function repeatblocks() { block1 = new block(); block1.size(150,150); block1.coordinates(randomtop(),randomleft());  }  setinterval(repeatblocks,1000); 

see fiddle https://jsfiddle.net/gustav1105/sb1vls38/

you need add var id = 1;

then in block function add this: this.block.id = "block"+id++;

var cheight = window.innerheight - 150; //size of block  var cwidth = window.innerwidth - 150;     var id = 1;    var block = function(block) {  	this.block = document.createelement('div');  	this.block.classname = 'block';	    this.block.id = "block"+id++;  	  	  	document.body.appendchild(this.block);    }    block.prototype.coordinates = function(top,left) {  	this.block.style.top =  top + 'px';  	this.block.style.left = left + 'px';  }    block.prototype.size = function(width,height) {  	this.block.style.width = width + 'px';  	this.block.style.height = height + 'px';  }      function randomtop() {  	var = math.random();  	var y = (i * (cheight - 0 + 1)) +0;  	var x = math.floor(y);  	return x;  }    function randomleft() {  	var = math.random();  	var y = (i * (cwidth - 0 + 1)) + 0;  	var x = math.floor(y)  	return x;  }      function repeatblocks() {  block1 = new block();  block1.size(150,150);  block1.coordinates(randomtop(),randomleft());    }    setinterval(repeatblocks,1000);
.block {  	position: absolute;  	border: 1px solid black;  }


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -