Reputation: 2199
I have a javascript function that switch from two different css files that affect my web-site. The problem is that the css are only partially applied with my function and I need to refresh the browser to get the entire new style.
Here is my function:
function switch_style ()
{
var head=document.getElementsByTagName('head')[0];
for (i = 0, link_tag = document.getElementsByTagName("link"); i < link_tag.length ; i++ )
{
if ((link_tag[i].rel.indexOf( "stylesheet" ) != -1) && link_tag[i].title)
{
if (link_tag[i].title == "normal")
{
head.removeChild(link_tag[i]);
}
}
}
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = '/templates/rhuk_milkyway/css/template_contrast.css';
head.appendChild(cssNode);
set_cookie( style_cookie_name, "contrast", style_cookie_duration );
}
As you can see i remove and then append a new style to the page header.
Is there a way to refresh the styling?
(It happens with all browser)
Upvotes: 2
Views: 3712
Reputation: 1625
I may be overlooking something, but why do you need to switch stylesheets when you can just add a new class to your html
or body
element?
Pros:
jQuery.toggleClass
(or element.className
, if you do not use jQuery) will do all the job.Con(s?):
Upvotes: 1
Reputation: 3897
The CSS
<link href="/css/main.css" rel="stylesheet"type="text/css" title="main" media="screen" />
<link href="/css/alt1.css" rel="alternate stylesheet" type="text/css" title="alt1" media="screen" />
The Javascript
function switch_style (title) {
var lnks = document.getElementsByTagName('link');
for (var i = lnks.length - 1; i >= 0; i--) {
if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) {
lnks[i].disabled = true;
if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false;
}}}
Upvotes: 0