Search code examples
javascripthtmldynamicappendchild

How do I create an object in JavaScript, that dynamically creates a div (with style properties and an id) and appends to my html page?


I'm trying to create an object in javascript that will dynamically create a line with style properties, and attach it to my page. I've seen other solutions that just create an element, but none that can be nicely fit into a single object.

Here's the code I'm trying:

function line(pos_x, pos_y, length, width, color, num) {
	this = document.createElement('div');
    this.style.left = pos_x + "%";
	this.style.top = pos_y + "%";
	this.style.length = length + "%";
	this.style.width = width + "%";
	this.style.backgroundColor = color;
    this.id = "line" + num;
    document.appendChild(this);
}

var line1 = line(10, 0, 100, 100, #2ecc71, 1);


Solution

  • Don't set this

    http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

    Also, there is style.width, but no length property

    To be visible, the div needs style.height > 0px

    function line(pos_x, pos_y, thickness, width, color, num) {
    	var line = document.createElement('div');
        line.style.left = pos_x + "%";
    	line.style.top = pos_y + "%";
    	line.style.height = thickness + "px";
    	line.style.width = width + "%";
    	line.style.backgroundColor = color;
        line.id = "line" + num;
        document.appendChild(line);
        return line;
    }
    
    var line1 = line(10, 0, 10, 100, #2ecc71, 1);