Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Style Sheet javascript

Tags:

javascript

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 this:

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 to the style sheets to change while pressing this buttons. I can't figure out why it is not working.

like image 718
Benji Avatar asked Jan 12 '13 11:01

Benji


People also ask

Can you change CSS with JavaScript?

JavaScript can change Css styles such as color, font size etc. of elements using some methods such as getElementById(), getElementByClassName() etc. In the following example font style and font size of the elements have changed using getElementById() method.

How do I switch between multiple CSS stylesheets?

Use rel="stylesheet" to link to the default style, and rel="alternate stylesheet" to link to alternative style sheets. This tells the browser which style sheet title should be selected by default, and makes that default selection apply in browsers that do not support alternate style sheets.


2 Answers

One guess would be the missing .css property, another would be the fact that onclick is not a function, but a result from invoking one:

Make all of .css a string and assign functions to onclick:

style1.onclick = function () { swapStyleSheet("default.css") };
style2.onclick = function () { swapStyleSheet("dark.css"); };
like image 73
Emil Ivanov Avatar answered Oct 18 '22 06:10

Emil Ivanov


Transform "default".css into "default.css". Do the same for dark.css.

Then onclick takes a function as a value.

style1.onclick = function () { swapStyleSheet("default.css") };
style2.onclick = function () { swapStyleSheet("dark.css") }; 
like image 32
Libert Piou Piou Avatar answered Oct 18 '22 07:10

Libert Piou Piou