I'm trying to bind divs with an object such that the divs have methods that can be acted upon. In particular I want when a user to clicks on a a div, for it to start moving across the screen, then if you click another div, it too starts moving.
For some reason my this.element inside the moveCarForward method function is undefined.
function Car(element) {
this.element = element;
this.element.addEventListener("click", function() {
this.style.border = "3px solid hotpink";
startDrive();
}, false);
startDrive = function() {
this.carDrivingInterval = setInterval(moveCarForward, 3000);
}
moveCarForward = function() {
this.element.style.x = this.element.offsetLeft + 10 + "px";
}
}
var arrayCarsElements = document.getElementsByClassName("car");
var arrCar = [];
for (var i = 0; i < arrayCarsElements.length; i++) {
arrCar[i] = new Car(arrayCarsElements[i]);
}
<div class="car" id="tesla" style="width: 50px; height: 50px; background: #ccc; margin-bottom: 10px;"></div>