0

I have html page and I want to change page styles using color switcher. I try to add css files to page by click on color-list div.

files hierarchy

index.html

css(folder)
-style2.css
-style3.css

js(folder)
-my.js

My html

<div class="settings-section color-list">
    <div class="first"></div>
    <div class="second"></div>  
</div>

Also I try to use jQuery

$('.color-list .first').on('click', function(){
    $("head").append($("<link rel='stylesheet' href='../colors-css/style2.css' type='text/css' media='screen' />"));
});

$('.color-list .second').on('click', function(){
    $("head").append($("<link rel='stylesheet' href='../colors-css/style3.css' type='text/css' media='screen' />"));
});

But it doesn't work. I can't add css files to head

  • 2
    Possible duplicate of [Load external css file like scripts in jquery which is compatible in ie also](http://stackoverflow.com/questions/2685614/load-external-css-file-like-scripts-in-jquery-which-is-compatible-in-ie-also) – Developer Jan 12 '17 at 10:54

5 Answers5

0

The reference to the file must start from your html and so you must use colors-css/style2.css instead of ../colors-css/style2.css:

$("head").append($("<link rel='stylesheet' href='colors-css/style2.css' type='text/css' media='screen' />"));
RWAM
  • 6,760
  • 3
  • 32
  • 45
0

Try this..

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/style1.css"
}).appendTo("head");
Hardik Kalathiya
  • 2,221
  • 1
  • 18
  • 28
0

You can add default link tag and on jquery click event set respective href

HTML Markup:

<link id="dynamicCSS" rel='stylesheet'  href='#' type='text/css' media='screen' />

jQuery Code:

$(document).ready(function(){

    var dynCSSk= $("#dynamicCSS");

    $('.color-list .first').on('click', function(){
         dynCSSk.attr("href","colors-css/style2.css");
    });

    $('.color-list .second').on('click', function(){
        dynCSSk.attr("href","colors-css/style3.css");
    });

});
Satinder singh
  • 10,100
  • 16
  • 60
  • 102
0

You can solve your problem by two way

1) - Create a CSS class in your CSS file with a class

.list-style{
   backbround : red;
}
  • In your jQuery write following:

    $('.color-list .first').addClass('list-style');

2) - user the below query

$('.color-list .first').css('background','green');
NARGIS PARWEEN
  • 1,489
  • 3
  • 16
  • 26
0

Try this hope it will help you.

$(document).on("click",".color-list div",function(){

var currentCssUrl=$(this).attr('id');
$.ajax({
url : currentCssUrl,
success : function(data){        
$("<style></style>").appendTo("head").html(data); 
}
});

});

Please find the below screenshot

http://prntscr.com/dunw7l

Nagaraju Kasa
  • 124
  • 10