MrMeeseeks
MrMeeseeks

Reputation: 9

Javascript constructor/OOP

I'm pretty new to javascript and I'm trying to recreate this: https://ibb.co/hh45jH

new Box(0, 0, 20, 30, "#007", parentDiv)

doesn't produce anything at all and I'm not quite sure why. I want it to produce a colored div with the above specifications

This is my code so far:

class Box {
  constructor(xPosition, yPosition, width, height, backgroundColor, parentElement) {
    var div = document.createElement("div");
    div.style.width = width;
    div.style.height = height;
    div.style.background = backgroundColor;
    style.position = "absolute";
    style.top = yPosition;
    style.left = xPosition;
  }

  function draw() {
    var parent = document.getElementById("parentDiv");
    new Box(0, 0, 20, 30, "#007", parentDiv)
  }
}
window.addEventListener("load", draw);
.parentDiv {
  width: 500px;
  height: 500px;
  background-color: red;
}
<div class="parentDiv"></div>

I want the above JavaScript code to produce a new div with the given instructions (color, height, width and so on) and then place it in the parentDiv just like in the example (link above).

Upvotes: -1

Views: 54

Answers (2)

ReadyFreddy
ReadyFreddy

Reputation: 933

As you can see on my snippet, after you define your class properly, you can create an object by this class and use a function from this object to draw it like that.

class Box {
  constructor(xPosition, yPosition, width, height, backgroundColor) {
    this.element = document.createElement("div");
    this.element.style.width = width+"px";
    this.element.style.height = height+"px";
    this.element.style.background = backgroundColor;
    this.element.style.position = "absolute";
    this.element.style.top = yPosition;
    this.element.style.left = xPosition;
  }
  
  draw(){
  var parentDiv = document.getElementById("parentID");
  var newBox = new Box(0, 0, 20, 30, "#007");
  parentDiv.append(newBox.element);
  }
}

const newBoxObj = new Box();


window.addEventListener("load", newBoxObj.draw());
<div id="parentID"></div>

Upvotes: 0

Robdll
Robdll

Reputation: 6263

I made few changes to your snippet. Check this out and fell free to comment if you have any doubt

class Box {
  constructor(xPosition, yPosition, width, height, backgroundColor) {
    this.element = document.createElement("div");
    var style = this.element.style;
    style.width = width + "px";
    style.height = height + "px";
    style.background = backgroundColor;
    style.position = "absolute";
    style.top = yPosition;
    style.left = xPosition;
  }
}

function draw() {
  let parentDiv = document.getElementById("parentDiv");
  let newBox = new Box(0, 0, 20, 30, "#557");
  parentDiv.append(newBox.element);
}


window.addEventListener("load", draw);
#parentDiv {
  width: 500px;
  height: 500px;
  background-color: red;
}
<div id="parentDiv"> asd </div>

Upvotes: 0

Related Questions