jQuery Add and Remove stylesheets

Posted By: Ian on Jan 24, 2012 in JQuery
Last modified on February 26th, 2014 at 11:27 am,

If your looking to enhance the experience of your visitors by offering them the ability of changing the layout and or colours on your webpage then this jQuery snippet could be handy for you.

With the use of cookies or even better the new HTML5 local storage feature the users preferences will be saved on there computer.

Using local storage is easier to code and quicker than using php and cookies and remember that’s what jQuery is all about “Write Less, Do More”.


Remove stylesheet

To remove a stylesheet simply give it an id
<link href=”cssFolder/sheet2.css” rel=”stylesheet” type=”text/css” id=”sheet2″>
And insert the following script just before </body> tag

<script type="text/javascript">
$(document).ready(function () {
jQuery('#sheet2').remove();
});
</script>

Demo


Add stylesheet

To Add a stylesheet insert the following script just before </body> tag

<script type="text/javascript">
$(document).ready(function () {
$('head').append('<link href="cssFolder/sheet2.css" rel="stylesheet" id="banSheet" />');
});
</script>

Demo


Although i have used document ready in the snippets above i have used the click function in the 2 demo files just to give you an idea of what can be done.


Add stylesheet from remote site

To Add a stylesheet from a remote site insert the following in your page

<input type="text" id="styleSheet" value="" />
<button id="style">Click me to add the stylesheet</button>

<script type="text/javascript">
$("#style").click(function () {
var from = $("input#styleSheet").val();
$('head').append('<link href='+from+' rel="stylesheet" id="sheet2" />');
alert('Stylesheet added! '+from);

});
</script>

Demo

Bored?

Have a go yourself at designing a simple colour changer or text re-sizer for your page.

AnonymousIan.J.Gough

Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

Discussion - 2 Comments

  • Jason Jason Sep 19, 2012 

    Hey Ian,

    This is extremely close to the type of thing I’m looking for. I’m looking to be able to add a stylesheet, but instead of having one already created and just hitting a button to switch them out, I’m looking to be able to paste in a link to any external style sheet and clicking a submit button and have it use that style sheet. Do you know how the code could be modified to do that?

    Reply

leave a comment

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,
Ian.J.Gough

protected by copyscape duplicate content check

Categories


Powered by Banner Bar 125