A colleague of mine asked me how to apply a stylesheet to a web page dynamically using jQuery and I had never done such a thing but my first thought was that is must be pretty simple. I've spent a lot of time thinking of so many things other than web et. al. so it was nice to delve into some of that stuff again. Check out the live demo
As we know stylesheets are defined in the head section of an html file like this
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
head>
<body>
...
html>
Now, say that we want to apply another stylesheet dynamically after the fact, so to speak, triggered by some event. This could be a button click or some other arbitrary event that is triggered. So, what we want to do is simply insert a new element into the head section of the page DOM. This can be done in a couple of lines of jQuery:
$(document).ready(function () {
$("a").click(function () {
$('head').append('');
});
});
The key is at what time we add the link to the style sheet. The first line in the code above repeated here asserts that the DOM is ready for manipulation.
$(document).ready(function () {
//...
});
The second part repeated here adds a click event to all hyperlinks in the page.
$("a").click(function() { //...
And the very task is performed by the last piece of code where the head element is appended with a new link element.