I am trying to add a <div> using JavaScript and then change its width/height/top/left attributes. But when I use the XHTML 1 Transitional doctype, it stops working.
This is how I am creating the <div>:
var div=document.createElement("div");
document.body.appendChild(div);
div.innerHTML='<div id="myID" style="z-index:9998;border: 1px solid #000000;
border-radius:3px;position: absolute; display: block;top:-10000;left:-10000;
width:400; height:400;"></div>';
So initially myDiv is not visible to user as its left and top are out of the screen
Then on some click action I am doing the following:
var myDiv=document.getElementById("myID");
myDiv.style.top=200;
myDiv.style.left=200;
This works fine if I do not put a doctype in the HTML. As soon as I put the doctype, it stops working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
With the doctype, it stops accepting top/left/width/height values. But if I set the width/height/top/left values with units (i.e. px) then it works fine.
myDiv.style.top="200px";
myDiv.style.left="200px";
So, what is the impact of the doctype on the execution of JavaScript while modifying the style (or may be other things as well)?
Using raw numbers is technically invalid, even if the browser is letting you get away with it when you’re not using a doctype (browsers do lots of funky things when you don’t use a doctype).
The style properties really are like the CSS properties, strings with units on them. So “200px” is correct, 200 is incorrect. The properties (
left, for instance) can be lengths like “200px” or “10em”, or percentages (orautoorinherit). (Those links are to the CSS 2.1 spec.)You also need to include units in your string when creating the
myIDdiv: