Binding timed events to DOM object with JavaScript

3967 views javascript
3

I'm trying to bind setInterval event to DOM objects. HTML and CSS is obsolete in this example. Tried different approaches but none seem to work. What am I missing here ?

window.onload = function() {
    for (let index = 0; index < 20; index++) {
        let x = new Box(Math.floor((Math.random() * 100) + 1), index + (index * 10), Math.floor((Math.random() * 100) + 1), 5);
        
    }
}
var id = 0;

class Box{
    constructor(x, y, size, speed){
        this.speed = speed;
        this.x = x;
        this.y = y;
        this.size = size;
        this.id = id;
        id++;
        this.spawn();
        this.move(this.id);
    }
    spawn(){
        let x = document.createElement("div");
        x.setAttribute("id", this.id);
        x.setAttribute("class", "box");
        x.style.top = this.y + 'px';
        x.style.left = this.x + 'px';
        x.style.width = this.size + 'px';
        x.style.height = this.size + 'px';
        document.body.appendChild(x);
        
    }
    move(id){
        setInterval(function() {
            document.getElementById(id).style.left = this.speed + 'px';
            this.speed += 5;
        }, 10);
    }
    
}

answered question

1 Answer

13

The this in setInterval doesnt refer to the object you want, you need to pass in this when calling move, also they dont have a position

window.onload = function() {
    for (let index = 0; index < 20; index++) {
        let x = new Box(Math.floor((Math.random() * 100) + 1), index + (index * 10), Math.floor((Math.random() * 100) + 1), 5);
        
    }
}
var id = 0;

class Box{
    constructor(x, y, size, speed){
        this.speed = speed;
        this.x = x;
        this.y = y;
        this.size = size;
        this.id = id;
        id++;
        this.spawn();
        this.move(this.id, this);
    }
    spawn(){
        let x = document.createElement("div");
        x.setAttribute("id", this.id);
        x.setAttribute("class", "box");
        x.style.top = this.y + 'px';
        x.style.left = this.x + 'px';
        x.style.width = this.size + 'px';
        x.style.height = this.size + 'px';
        document.body.appendChild(x);
        
    }
    move(id, _this){
        setInterval(function() {
            document.getElementById(id).style.left = _this.speed + 'px';
            _this.speed += 5;
        }, 10);
    }
    
}
div {
  position: relative;
  background-color: #f00;
}

posted this

Have an answer?

JD

Please login first before posting an answer.