4

Good day!

I want to add and remove CSS files according to the size of the list. My code is as follow:

$("#size_storedList").ready(function(){
    var list_size = $("#size_storedList").attr('value');
    if(list_size <= 4){
        if ($("link").is('.size5')){
            $('link.size5').removeClass();
        }
        if ($("link").is('.size6')){
            $('link.size6').removeClass();
        }
        $('head').append('<link class="size4" rel="stylesheet" href="css/stored_list/list_size4.css" type="text/css" />');
    } else if(list_size == 5){
        if ($("link").is('.size4')){
            $('link.size4').removeClass();
        }
        if ($("link").is('.size6')){
            $('link.size6').removeClass();
        }
        $('head').append('<link class="size5" rel="stylesheet" href="css/stored_list/list_size5.css" type="text/css" />');
    } else if(list_size == 6){
        if ($("link").is('.size4')){
            $('link.size4').removeClass();
        }
        if ($("link").is('.siz5')){
            $('link.size5').removeClass();
        }
        $('head').append('<link class="size6" rel="stylesheet" href="css/stored_list/list_size6.css" type="text/css" />');
    }
});

But it is kind of messy. What can i do to minimize the checking if the file already exists or not so that i can remove it

if ($("link").is('.size5')){
            $('link.size5').removeClass();
}

Thank you.

2 Answers 2

8
<link rel="stylesheet" href="default.css" type="text/css">

<ul>
  <li><a id="css-red" href="#red">Red</a></li>
  <li><a id="css-blue" href="#blue">Blue</a></li>
  <li><a id="css-green" href="#green">Green</a></li>
</ul>

$(document).ready(function() {
  // red
  $("#css-red").click(function() {
    $("link[rel=stylesheet]").attr({href : "red.css"});
  });
});

Above concept is different from you, but I think this will be a good idea. You can customize same to your current code.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, Very nice! If you have multiple stylesheets you can use $("link[rel=stylesheet]")[index] if you know the order, or, you can use $("link[rel=stylesheet]").each to peruse them.
if we have multiple style sheets then? now the existing one is replacing
1

You could use data-* attributes on the body tag and save in, let's say data-loaded-css, the url of the currently active css file.

also see $.data()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.