Angelo Badellino
Angelo Badellino

Reputation: 2199

How to refresh the style of a page after css switch

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

Answers (2)

unclenorton
unclenorton

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:

  • 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.

Upvotes: 1

Philar
Philar

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

Related Questions