Change javascript stylesheet

I got this HTML code:

<head> <script type="application/javascript" src="javascript.js"> <link id="pagestyle" href="default.css" rel="stylesheet" type="text/css" /> </head> <body> <button id="stylesheet1" > Default Style Sheet </button> <button id="stylesheet2" > Dark Style Sheet </button> </body> 

And in javascript.js I got the following:

 function swapStyleSheet(sheet) { document.getElementById("pagestyle").setAttribute("href", sheet); } function initate() { var style1 = document.getElementById("stylesheet1"); var style2 = document.getElementById("stylesheet2"); style1.onclick = swapStyleSheet("default".css); style2.onclick = swapStyleSheet("dark".css); } window.onload = initate; 

I want the stylesheets to change when these buttons are clicked. I can not understand why it does not work.

+6
source share
2 answers

It was assumed that this would be the missing .css property, the other is the fact that onclick not a function, but the result of a call from it:

Make the entire .css line and assign the onclick function:

 style1.onclick = function () { swapStyleSheet("default.css") }; style2.onclick = function () { swapStyleSheet("dark.css"); }; 
+4
source

Convert "default" .css to "default.css". Do the same for dark.css.

Then onclick takes the function as a value.

 style1.onclick = function () { swapStyleSheet("default.css") }; style2.onclick = function () { swapStyleSheet("dark.css") }; 
+2
source

All Articles