Changing CSS using a button and Java Script

I have recently been making a website and I want my CSS to change when a button is pressed and change back once the button is pressed again. Doing some research I came up with this code and java script but I can’t get it to work.

<html>
<head>
    <link id="stylesheetold" href="chollerton.css" rel="stylesheet" type="text/css"/>
    <link id="stylesheetnew" href="alternate.css" rel="stylesheet" type="text/css"/>
    <meta charset="UTF-8">
    <title>Chollerton Tearooms Home Page</title>
    <script type="text/javascript">
        var CssToggler =
            {
            init: function()
            {
                var toggle = document.getElementById("toggler");

                toggle.addEventListener("click", CssToggler.clickListener, false);
            },
            clickListener:function()

            {
                var stylesheetold = document.getElementById("stylesheetold");
                var stylesheetnew = document.getElementById("stylesheetnew");
                stylesheetold.disabled = !stylesheetold.disabled;
                stylesheetnew.disabled = !stylesheetnew.disabled;
            }

        }

        Core.start(CssToggler);
    </script>
    <script type="text/javascript">
        function changeTextSize(){
            document.getElementById('maintext').style.fontSize = "large";
        }
    </script>
</head>

<button id="toggler">Change CSS</button>

Any help would be much appreciated.

Here are some links with better ways to do what you want.
https://www.developphp.com/video/JavaScript/Change-CSS-Class-Style-className-Toggle-Tutorial

http://www.dustindiaz.com/seven-togglers/

I didn’t try your script but what are you seeing in console?

Have you tried moving the JavaScript to just before the </body> tag so that it correctly loads after the rest of the page instead of incorrectly loading before the HTML it is trying to interact with.

2 Likes

This really needs to be pinned to the top of the forum, such a common cause of confusion. Can we add FAQ’s?

1 Like

Possibly a little off topic, but here is a css only method to switch styles.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.