1

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);
    }
    
}

1 Answers1

0

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;
}
Chris Li
  • 2,451
  • 1
  • 6
  • 23
  • They did have position in my css, thanks for helping, ill try understand that now :) Just wondering why spawn() function works without passing 'this'. – Cezary Stasiak Sep 15 '18 at 18:08
  • ah ok, javascript scoping can be confusing sometimes, you can read more about how `this` works in this question https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Chris Li Sep 15 '18 at 18:13
  • This refers to a caller so in my case it referred to move() function therefor didn't work. – Cezary Stasiak Sep 15 '18 at 19:00