Forum Moderators: not2easy

Message Too Old, No Replies

Can I dynamically link to a css file?

         

lisboa

9:30 pm on Mar 11, 2005 (gmt 0)

10+ Year Member



<link rel="stylesheet" type="text/css" href="code/001.css">

Can I change the href path "code/001.css" to a javascript variable? Something like: href="'code/'+var+'.css'"

Can somebody help me?

createErrorMsg

10:18 pm on Mar 11, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Regular HTML cannot do this. Some sort of scripting is needed.

Javascript:
function swapStyle(style){
tag = document.getElementsByTagName('link')[0];
tag.href = style;
}
* This is super simplified and unlikely to work cross-browser. A real JS styleswitcher has to do several other important things, such as store the value in a cookie if you want the style swap to persist through browsing the site (otherwise, a JS swapped stylesheet reverts back to the original when a new page is visited).

PHP:
<?php echo("<link rel='stylesheet' href='$style' />")?>
* This requires that your server is set up to parse your page code as PHP, and that the php variable $style is set when the page loads.

There is a good article on ALA called "Alternative Style" that details making a persistent js styleswitcher if you want users to be able to select a style. If you are looking to use a setting made on the server-side to deliver a specific stylesheet, a PHP script is best.

For more info on using either one of these scripting languages to swap stylesheets, run a search on google or post specific questions in the appropriate forums.

WebmasterWorld JavaScript Forum [webmasterworld.com]
WebmasterWorld PHP Forum [webmasterworld.com]

cEM