Date: 07/11/11 (Web Development) Keywords: css, html, java [Edit: fixed CSS syntax in these examples. The development code is fine in that regard.] Using Firefox 5 on Windows 7, I ran into two related problems that must be common enough for there to be standard workarounds. 1. CSS is not applied until after Javascript runs. Given the CSS: #id { width: 50px; } document.getElementById("id").style.width is undefined. This is using jquery's $(document).ready() which runs after everything else is supposed to be loaded. The standard body onload will run even earlier, with less of a chance that the CSS will be loaded if the problem is due to a race. Javascript can see the CSS style if it is set in the contents of an HTML style="" attribute, but you lose the benefits of CSS if you have multiple tags sharing the same style.
div.myclass { width: 50px; } /* CSS */ var node = document.createElement("div"); // JS node.setAttribute("class", myclass"); // CSS is not applied. node.className = "myclass"; // CSS is not applied. One solution to this one is to code every single CSS style change in Javascript using the DOM, but I would prefer not to have to do that. What are the best practices in these situations?
|