2

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)

Angelo Badellino
  • 2,141
  • 2
  • 24
  • 45

2 Answers2

1

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:

  • Faster switching. You do not have to wait until your new css is loaded - the alternate styles can be included in the original stylesheet.
  • Simpler. jQuery.toggleClass (or element.className, if you do not use jQuery) will do all the job.
  • Works everywhere.

Con(s?):

  • You have to add the new class to all the selectors in css.
unclenorton
  • 1,605
  • 11
  • 19
0

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;
    }}}
Philar
  • 3,887
  • 1
  • 24
  • 19
  • This solution does not work because the disable attribute is note correctly recognised by all the browser. – Angelo Badellino Nov 02 '10 at 09:21
  • Tested this on the following browsers and platforms Mac OSX 10.5.8- Mozilla 3.6.12, Chrome 7.0.517.41, Safari 5.0 Win XP SP3 -IE8 and it works for me. – Philar Nov 02 '10 at 09:42
  • 1
    http://stackoverflow.com/questions/4064963/why-doesnt-setting-the-disabled-property-of-a-link-tag-via-javascript-work-i/4065089#4065089 – Angelo Badellino Nov 02 '10 at 09:54