Dynamically add CSS to HTML/JavaScript

I had to show certain HTML elements based on the client device, e.g. show elements on a desktop but hide on a mobile/tablet. It was easy to dynamically use JQuery to hide/show/remove the elements. But CSS doesn’t work like that. Here’s some trick I borrowed from a blog to do the same:

<script type="text/javascript">
    if(!isMobile()) {
        /**
        * function to load a given css file 
        */ 
        loadCSS = function(href) {
            var cssLink = $("<link rel='stylesheet' type='text/css' href='"+href+"'>");
            $("head").append(cssLink); 
        };
        // load the css file for thumbnail scroll
        loadCSS("../../css/thumbnail_scroll.css");
    }	

</script>

Similary, if a JS file was to be added dynamically,

<script type="text/javascript">
    if(!isMobile()) {
        /**
        * function to load a given js file 
        */ 
        loadJS = function(href) {
            var jsLink = $("<script type='text/javascript' src='"+src+"'>");
            $("head").append(jsLink); 
        };
        // load the js file for thumbnail scroll
        loadJS("../../js/utils.js");
    }	

</script>
Advertisements

One thought on “Dynamically add CSS to HTML/JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s