how to Change Style Sheet Using Javascript

It may be useful sometimes to provide your visitors with the option to change the appearance of your website. May be you want to provide theme support for your site. Or you may simply want to provide a bigger font size version of your site for older users who may not be able to read the small-sized text you use by default. This post describes how you can use JavaScript to dynamically change the cascading style sheets, or CSS, of your website.

HTML Code

<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<button onclick="swapStyleSheet('dark.css')"> Dark Background </button>
<button onclick="swapStyleSheet('blue.css')"> Blue Background </button>
<button onclick="swapStyleSheet('default.css')"> Default Background </button>

JavaScript Code

<script type="text/javascript">
    function swapStyleSheet(sheet)
    {
        document.getElementById('pagestyle').setAttribute('href',sheet);
    }
</script>

Complete page source here.

<!DOCTYPE html>
<html>
    <head>
        <title>Demo</title>
        <link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
        <script type="text/javascript">
            function swapStyleSheet(sheet)
            {
                document.getElementById('pagestyle').setAttribute('href',sheet);
            }
        </script>
    </head>
    <body>
        <button onclick="swapStyleSheet('dark.css')"> Dark Background </button>
        <button onclick="swapStyleSheet('blue.css')"> Blue Background </button>
        <button onclick="swapStyleSheet('default.css')"> Default Background </button>
    </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *