Question:

Dynamic loading CSS via JavaScript?

by  |  earlier

0 LIKES UnLike

Right...

I'm basically wondering how I would go about having specific StyleSheets load at given dates. I've Googled for a while now and all I can really find are scripts that will load a StyleSheet at random. I would normally butcher this code for my own benefit, but seeing as though I don't know much JS, it wouldn't be much help.

Can anybody point me in the right direction?

Please.

2 free Internets (and 10 points, of course) for the selected answer!

=)

 Tags:

   Report

3 ANSWERS


  1. Might get a better answer posting your question in the JavaScript section of this forum:

    http://www.webdeveloper.com/forum/forumd...

    Ron


  2. <html>

    <head>

    <script type="text/javascript">

    // path to CSS files

    var styleDir = '';

    // each pair is a the date on which to begin using the

    // corresponding CSS file and from which to continue

    // using that file until the next file's trigger-date

    // is encountered

    var cssDatesFiles = [

    ['Jun 1, 2008', 'June.css'],

    ['Jul 1, 2008', 'July.css'],

    ['Aug 1, 2008', 'August.css'],

    ['Sep 1, 2008', 'September.css']

    ]

    function addCssFileByDate() {

    var cssFile;

    // search in reverse, until the first date is encountered

    // that is prior to today's date - the corresponding CSS

    // file is the one to use

    for (var i = cssDatesFiles.length -1; i > -1; i--) {

    if (todayLaterThan(cssDatesFiles[i][0])) {

    cssFile = cssDatesFiles[i][1];

    // once found, quit searching

    break;

    }

    }

    // now add a new link element to the head to include

    // the reference to the CSS file

    var d = document;

    var h = d.getElementsByTagName( 'HEAD' )[0];

    var l = d.createElement( 'LINK' );

    l.type = 'text/css';

    l.rel = 'stylesheet';

    l.href = styleDir + cssFile;

    h.appendChild( l );

    }

    function todayLaterThan(d) {

    var testDate = new Date(d);

    var today = new Date();

    return today > testDate;

    }

    addCssFileByDate();

    </script>

    </head>

    <body>

    <p> content here </p>

    </body>

    </html>

  3. depend where you want to load your CSS

    header or body

    (Generic pseudo code for idea purposes only)

    //assuming it's in the header

    <script  type="text/javascript" >

    if ( mydate > today() )  

    {

       document.write("<link rel='stylesheet' type='text/css' media='screen' href='http://l.yimg.com/h/02637/css/answ...

    ")

    }

    else

    {

    document.write("<link rel='stylesheet' type='text/css' media='screen' href='http://l.yimg.com/h/02637/css/some...

    ")

    }

    }

    </script>

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.