0

I am a photographer with a limit knowledge of HTML/CSS and almost no knowledge of javascript. I am trying to build my own own website and I wanted to have an option to switch between light/dark background, for a better viewing experience when looking at my pictures. I have found a code to swap between CSS (light/dark).

HEAD HTML:

<link rel="stylesheet" id="pagestyle" type="text/css" href="CSS/light.css" >
<link rel="alternate stylesheet" tittle="dark" type="text/css" href="CSS/dark.css" >
<script src="scripts/styleswitcher.js" type="text/javascript"></script>

BODY HTML:

<button id="light"> Light </button>
<button id="dark"> Dark </button>

And I'm trying to use the javascript code found here. Javascript:

var setdark = function () {
        $('#head').append('<link rel="stylesheet" href="CSS/dark.css" type="text/css" />');
    },
    setlight = function () {
        $('link[rel=stylesheet][href="CSS/dark.css type="text/css"]').remove();
    };

$("#light").click(function () {
    localStorage.setItem('color', 'light');
    setlight();
});

$("#dark").click(function () {
    localStorage.setItem('color', 'dark');
    setdark();
});

if (localStorage.getItem('color') == 'light') {
    setlight(); 
} 

else if (localStorage.getItem('color') == 'dark') {
    setdark();
}

I edited the code in the hope I can make it work on my website. But it isn't working. What am I doing wrong?

Community
  • 1
  • 1
  • 1
    Your code is jQuery, not plain javascript, so you need to load the jquery library too. Before you load `styleswitcher.js`. Get it here: https://jquery.com/. Also, `styleswitcher.js` should be loaded at the end of the document, not in the head - unless you wrap all of your jQuery code in a [document ready handler](https://learn.jquery.com/using-jquery-core/document-ready/) – Turnip Mar 22 '17 at 13:25

4 Answers4

1

You should add

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>

before

<script src="scripts/styleswitcher.js" type="text/javascript"></script>

then

$(document).ready(function(){
var setdark = function () {
    $('#head').append('<link rel="stylesheet" href="CSS/dark.css" type="text/css" />');
},
setlight = function () {
    $('link[rel=stylesheet][href="CSS/dark.css type="text/css"]').remove();
};

$("#light").click(function () {
    localStorage.setItem('color', 'light');
    setlight();
});

$("#dark").click(function () {
    localStorage.setItem('color', 'dark');
    setdark();
});

if (localStorage.getItem('color') == 'light') {
    setlight(); 
} 

else if (localStorage.getItem('color') == 'dark') {
    setdark();
 }
})
Fan Yer
  • 377
  • 3
  • 7
1

You should load jQuery before using its plugins, and then call it until the dom and jquery ready.

I thought you'd better go through the js guide by Mozilla.

gyfh
  • 31
  • 2
0

You need to include jQuery into your project.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Your title</title>
  <link rel="stylesheet" id="pagestyle" type="text/css" href="CSS/light.css">
  <link rel="alternate stylesheet" tittle="dark" type="text/css" href="CSS/dark.css">
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="scripts/styleswitcher.js" type="text/javascript"></script>
</body>

</html>

And javascript that will trigger the switch

$(function () {
    var setdark = function () {
            $('#head').append('<link rel="stylesheet" href="CSS/dark.css" type="text/css" />');
        },
        setlight = function () {
            $('link[rel=stylesheet][href="CSS/dark.css type="text/css"]').remove();
        };

    $("#light").click(function () {
        localStorage.setItem('color', 'light');
        setlight();
    });

    $("#dark").click(function () {
        localStorage.setItem('color', 'dark');
        setdark();
    });

    if (localStorage.getItem('color') == 'light') {
        setlight();
    } else if (localStorage.getItem('color') == 'dark') {
        setdark();
    }
});

Note that order in which you load your JS files is very important, jQuery needs to be loaded first, than any other depended file.

The following is shorthand for document ready, it means that execute anything inside it after everything else loads that way you guard your self from unexpected errors when DOM does not load everything

$(function () {

}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ukaric
  • 428
  • 1
  • 7
  • 22
0

If you want to use plain, JS which I'd recommend it to you instead of using jQuery directly, try this approach.

I've commented every line to make it more understandable

// select the button to attach and event to it
var themeTogglerButton = document.querySelector('#themeToggler');

// check if there's a stored theme
var storedTheme = localStorage.getItem['theme'];

// if the theme is dark set the class on the body
if (storedTheme === 'dark') {
  document.body.classList.add('dark');
}

// attach and event when clicking the button
themeTogglerButton.addEventListener('click', function() {
  // the event consists on toggling a class on the body element
  document.body.classList.toggle('dark');

  if (document.body.classList.contains('dark')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.removeItem('theme');
  }
})
/* default style (without dark class) */

body {
  background: white;
}


/* style when body has the 'dark' class */

body.dark {
  background: black;
}
<button id="themeToggler">
 Toggle theme
</button>
David Lampon
  • 492
  • 3
  • 13
  • The code doesn't work? And is the preferred css stored somewhere? I was able to make a working css switch but whenever I refreshed the page or load another page, it reset back to default. – Letterdief Mar 22 '17 at 14:03
  • Yes, you were right. CSS comments were breaking the style load. Not it's fully functional. The theme reset on reload will happen with this solution too. Let me check for a local storage solution. – David Lampon Mar 22 '17 at 14:16
  • I've updated the code with the localStorage solution. It can't be tested in here because it's sandboxed and the fiddle has no access to the localStorage but should work on your local. Is your `java.js`on the same folder than the html file? – David Lampon Mar 22 '17 at 14:48
  • I fixed the problem: localstorage.getItem['theme']; **must be** localstorage.getItem('theme'); and now it's working perfect! Square brackets to round brackets :D – Letterdief Mar 22 '17 at 15:13
  • Just wanted to thank you again. You saved me a lot of work. I edited your code a bit, I tried to find a way to contact you so I could share my final work with, but I couldn't find it. So this will have to do, thank you! – Letterdief Mar 22 '17 at 18:24
  • Thank you for coming back to tell me. It's nice to know I've been helpful =) – David Lampon Mar 23 '17 at 08:46