Create Element with id and styles using pure JS

appendchild, createelement, function, javascript

Solution

You are not setting `style` property correctly. Rest of code is correct.

Here's an example

window.addEventListener("load", function(e) {
  var inButton = document.createElement("DIV"),
    body = document.body;
  inButton.id = "button";
  inButton.innerHTML = "Yahooooooooooooooo"; //For example

  inButton.style.height = "200px";
  inButton.style.width = "400px";
  inButton.style.position = "fixed";
  inButton.style.top = "50%";
  inButton.style.left = "50%";
  inButton.style.marginLeft = -1 * (this.width / 2);
  inButton.style.marginTop = -1 * (this.height / 2);

  body.appendChild(inButton);
}, false);

Problem

I build a small function appending an element with an id and styles. And know my question why does this code not work? ``` window.addEventListener("load",function(e){ var inButton = document.createElement("DIV"), body = document.body; inButton.id = "button"; inButton.style = function (){ height = "200px"; width = "400px"; position = "fixed"; top = "50%"; left = "50%"; marginLeft = -1*(this.width / 2); marginTop = -1*(this.height / 2); }; body.appendChild(inButton); }, false); ``` I use the following html: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="description"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta http-equiv="x-ua-compatible" content="ie=edge" /> <script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script> </head> <body> <script type="text/javascript" src="js/plugins.js"></script> <script type="text/javascript" src="js/main.js"></script> </body> </html> ``` The Js Code is inside the main.js. I checked the path again and again, but the path is totally correct.

Original source