J_Ocampo
J_Ocampo

Reputation: 475

Javascript-made Divs not displaying

I have a div (lets call it fatherDiv) with relative position and a fixed width and height.

I send this object to a javascript function (init) that creates 3 overlaying divs and puts them as fatherDiv's childs. Yet, these 3 overlaying divs are not displaying properly.

I want to have this outcome:

enter image description here

I'm trying to achieve this by using these javascript functions:

   function fabDiv(width, z) {

    var element = document.createElement("div");
    element.setAttribute("height", "200px");
    element.setAttribute("width", width.toString()+"px");
    element.setAttribute("position", "absolute");
    element.setAttribute("top", "0");
    element.setAttribute("left", "0");
    element.setAttribute("z-index", z.toString());

    return element;
}
function init(container, /*img1, img2, img3,*/ interval) {

    div1 = fabDiv(294, 3);
    div2 = fabDiv(265, 2);
    div3 = fabDiv(235, 1);

    container.appendChild(div1);
    container.appendChild(div2);
    container.appendChild(div3);

    div3.setAttribute("background-color", "lightblue");
    div2.setAttribute("background-color", "blue");
    div1.setAttribute("background-color", "darkblue");
}

Any advice is welcome. Thanks :)

PS: When i F12 on chrome to inspect the html elements created, i can see the divs in code but the little tooltip shows that they have no height (0px).

Upvotes: 1

Views: 51

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206209

DEMO

function fabDiv(width, bgCol) {  
    var el = document.createElement("div");  
    el.style.height = "200px";
    el.style.width = width+"px";
    el.style.position = "absolute";
    el.style.backgroundColor = bgCol;  
    return el;
}

function init(container, /*img1, img2, img3,*/ interval) {
    container.appendChild( fabDiv(294, "lightblue") );
    container.appendChild( fabDiv(265, "blue") );
    container.appendChild( fabDiv(235, "darkblue") );
}

var cont = document.getElementById('container');
init(cont);

Another way to do it:

DEMO

function CSS( el, prop, val ){
   if(!val && typeof prop == "object" ) for(var key in prop) el.style[key] = prop[key];
   else el.style[prop] = val;
   return el; 
}

function fabDiv( obj ) {
  var el = document.createElement("div");
  CSS(el, {height:"200px", width:obj.width+"px", position:"absolute", backgroundColor:obj.backgroundColor
  });
  document.getElementById(obj.appendTo).appendChild(el);
  return el;
}

function init() {
  fabDiv({width:294, backgroundColor:"lightblue", appendTo:'container'});
  fabDiv({width:265, backgroundColor:"blue", appendTo:'container'});
  fabDiv({width:235, backgroundColor:"darkblue", appendTo:'container'});
}

Upvotes: 1

Related Questions