Benji
Benji

Reputation: 635

Changing Style Sheet 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.

Upvotes: 17

Views: 47656

Answers (4)

The Creator
The Creator

Reputation: 1

 $('button').click(function() {
   let mainSheet = $('#pageStyle').attr('href');
   if(mainSheet == "default.css")
      $('#pageStyle').attr('href','dark.css');
   else
      $('#pageStyle').attr('href','default.css');
   });

Upvotes: 0

Dmitry
Dmitry

Reputation: 177

Hello it Won't work until you add onclick="" property in html So the final version will look like this: html

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

Javascript file

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");
}

Upvotes: -1

Libert KHE
Libert KHE

Reputation: 540

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") }; 

Upvotes: 3

Emil Ivanov
Emil Ivanov

Reputation: 37663

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"); };

Upvotes: 18

Related Questions