Powered by Blogger.

Add stylesheets dynamically with jQuery

 


Have you know how to apply a two or more different stylesheet to a web page dynamically using jQuery. It is so simple just keep in mind that we want to add dynamic stylesheet in head section so we will try to append another stylesheet by using append() method of jQuery.
As we know stylesheets are called 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, we want to apply another stylesheet dynamically after the fact, triggered by some event. This could be done on click or some other event that is triggered. So, we can able to add simply <link/> element into the head section of the page using append method. This can be done in a below given Jquery example:
$(document).ready(function () {
    $("a").click(function () {
        $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
    });
});
In the above given code, when user click the "a" tag then append method will triggered and style2.css applying to a head section of HTML file because $('head').append is used to add style in head section.

No comments