Search code examples
cssyui

update CSS class dynamically for a whole website


I have a reference site for a series of books, and I'd like to make it so that readers can avoid spoilers. The idea I had was to make a setup webpage where they click on a checkbox for each book from which they want to see info. I could then store that (somehow) as a cookie for each time that they visit the site, plus have it work for each page in the site. So, one page might have this:

<li class="teotw">Rand killed a Trolloc</li>

and another page might have

<li class="teotw">Nynaeve tugged her braid</li>

and that information would not show up on the page unless they had checked the box for the "teotw" book. My initial thoughts are to do something like toggling the CSS class value like this:

document.styleSheets[0]['cssRules'][0].class['teotw'] = 'display:none';  
document.styleSheets[0]['cssRules'][0].class['teotw'] = 'display:inherit';  

but I'm not sure if this is the best method. Firstly, it would only apply to the current document only so I'd need a way to re-apply it to each page they visit. I'm using YUI as well, if it matters. Any ideas on the best way of doing this?


Solution

  • There are many ways to implement it. You can use the YUI Stylesheet module (read its User Guide for how to use it) which will do what you're considering with cross-browser support and it's much easier to use than using the DOM directly.

    Another way would be to add classes to the body of the page. You can define styles like this:

    .teotw {
      display: none;
    }
    .teotw-visible .teotw {
      display: block;
    }
    

    With the following JS code:

    if (someCondition) {
      // show the hidden content
      Y.one('body').addClass('teotw-visible');
    }
    

    For the persistance of the visible state you can use cookies with the YUI Cookie utilty or local storage with CacheOffline. Code using cookies would look something like this:

    var body = Y.one('body');
    if (Y.Cookie.get('teotwVisible')) {
      body.addClass('teotw-visible');
    }
    // change the cookie 
    Y.one('#teotw-toggle').on('click', function (e) {
      var checked = this.get('checked');
      Y.Cookie.set('teotwVisible', checked);
      body.toggleClass('teotw-visible', checked);
    });
    

    You should probably store the different sections in a JS object and avoid hard-coding class names in every JS line. Or maybe use a convention between checkboxes IDs and section class names.