PDA

View Full Version : Calling CSS in Javascript



locbtran
03-13-2011, 05:32 PM
in HTML you can call CSS


<head>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<tr><td class="cssHere">Display</td></tr>

can you even call CSS in javascript?

document.writeln("<tr><td class="cssHere">" + Display + "</td></tr>");

if so how do you even call the "style.css"

thanks

djr33
03-13-2011, 05:35 PM
One option is to include the stylesheet in your <head> section in the HTML. Then it will be waiting for any dynamically generated Javascript.

If you need to load stylesheets dynamically (for example, different versions in different circumstances), then start here:
http://www.google.com/search?q=dynamically+call+external+css+with+javascript

Nile
03-13-2011, 06:33 PM
You can play around with:


<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<link href="styles/style.css" rel="stylesheet" type="text/css" />
<link href="styles/blue.css" rel="stylesheet" id="alt_blue" type="text/css" /> <!-- start off with this -->
<link href="styles/red.css" rel="alternative" id="alt_red" type="text/css" />
<script type="text/javascript">
var toggleStyle = function(id){
var newStyle = document.getElementById('alt_' + id);
if(newStyle == null) {
alert("Doesn't exist.");
return ;
}
for(var i = 0; i <= document.getElementsByTagName('link').length-1; i++){
if((document.getElementsByTagName('link')[i].id.substring(0,4) == "alt_")){
if(document.getElementsByTagName('link')[i].id != "alt_" + id){
document.getElementsByTagName('link')[i].rel = "alternative";
} else {
document.getElementsByTagName('link')[i].rel = "stylesheet";
}
}
}
};
</script>
</head>
<body>
<div id="page-wrap">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sem magna, convallis et feugiat vitae, placerat in tortor. Nam fermentum, ligula ac sodales luctus, libero dolor rutrum nisi, ac porttitor velit elit et elit. Sed ac elit sed tellus interdum convallis. In dignissim est quis tortor blandit condimentum. Aliquam lacinia, leo id luctus mattis, augue lectus facilisis quam, sit amet fermentum felis lectus ac massa. Maecenas nisi mauris, porttitor non interdum at, lacinia vitae diam. Praesent in metus odio. Curabitur condimentum massa ac velit volutpat placerat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sollicitudin nibh vitae lectus commodo ornare. Sed ac lacus lacus, sed tempor eros. Morbi non lobortis ligula. Suspendisse elementum lorem sit amet diam feugiat tincidunt. Mauris eleifend nisi vitae velit viverra vel aliquet metus vulputate. Praesent orci ligula, ultrices vitae fermentum molestie, euismod ac lectus. Aliquam est ligula, sodales ut pharetra a, varius eget tortor.</p>
<div class="blue" onclick="toggleStyle('blue');"></div>
<div class="red" onclick="toggleStyle('red');"></div>
</div>
</body>
</html>