In one of my earlier posts, I demonstrated how to Programmatically Retrieve StyleSheet Url’s Referenced in your Page using JavaScript. In this post, here’s a piece of JavaScript code that demonstrates how you can programmatically reference a CSS link on a page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="CSS/FloatDes.css" rel="stylesheet"
title="Float layout" type="text/css" />
<script type="text/javascript">
function addCSS() {
var headtg = document.getElementsByTagName('head')[0];
if (!headtg) {
return;
}
var linktg = document.createElement('link');
linktg.type = 'text/css';
linktg.rel = 'stylesheet';
linktg.href = 'CSS/RoundCorners.css';
linktg.title = 'Rounded Corners';
headtg.appendChild(linktg);
}
</script>
</head>
<body onload="addCSS()">
</body>
</html>
The code shown above creates a link element(with properties) and appends it as a child to the <head> section. You can use this technique to let users choose styles and change the appearance of the page.
How to do it in an ASP.NET page?
ReplyDelete@Jumler
ReplyDeleteI would imagine, but feel free to correct me, server technology ( such as ASP or JSP ) shouldn't have any effect on it.
Essentially, as long as it is present in the browser, it will have HEAD element and thus the above JS will work.
shouldn't the line:
ReplyDelete"headtg.appendChild(link);"
actually read:
"headtg.appendChild(linktg);"
Like this alot, thanks so much for posting!
-AT
Yes that's a typo and thanks for pointing it out. The code has been updated!
ReplyDeleteHow can I make a link to get back to the original CSS?
ReplyDeleteYou can also use wjs library for that :
ReplyDeletewjs.use('CssLink', 'yourcss.css');