Can anybody help me out with my Darkmode? - javascript

I want do have a basic Darkmode linked to a key press. I'am a Beginner in JavaScript and i cannot get it to work. I want it like, you press a key, the Darkmode turns on with a Cookie over js-cookie, and I press the same Key again to turn off the Darkmode and delete the cookie. Can anybody help me?
There is my Code:
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
let zahl = 1;
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}
if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Edit:
Ok i've got it:
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
if (CookieDarkMode) {
Cookies.set("Darkmode", "An");
}else {
Cookies.remove("Darkmode");
}
}
};
var DarkCookie = Cookies.get("Darkmode")
if (DarkCookie == 'An') {
CookieDarkMode = true;
toggleDarkMode();
}

You don't have to store a number. You can just get the previous cookie value with a boolean
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
}
};
body {
background-color: ghostwhite;
}
.dark-mode {
background-color: black;
color: white;
}
<body>
<p>Lorem Ipsum</p>
</body>

your problem is on your checkKeyPress function, you always check for the zahl value, but it will always start as 1.
for demostration purposes you are doing this basically:
function sum(){
let zahl = 1;
zahl++
console.log(zahl)
}
// you will never see a 3, because you are creating `zhl`
// in each call with a value of 1
sum();
sum();
sum();
sum();
therefore, each time you check for the zahl variable, it will be 1 and will always enter the if that turns on the darkmode.
the solution for your code would be to move the zahl variable outside the function scope:
let zahl = 1; // outside the function scope
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}else if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
dark(); //you should call dark here as well to toggle to the other mode.
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
note: it doesn't look like the best implementation, it would be easier to read if you use a boolean for the state of the mode or if you want multiple types, you can use the name as a key for each of the modes.

Related

javascript add and remove className, keep setting

I want to make a button for night and day mode.I found this link but it doesn't work for me.
when i click the button, it applies css to change background and text color and button value which is night to day but if i click button again it doesn't work. it keeps execute "if" part not "else" part.
//nightmode
var mode = localStorage.getItem("mode");
if (mode != null) {
document.getElementById("body").classList.add(mode);
}
document.getElementById("nightButton").onclick = function() {
var nightButton = document.getElementById("nightButton")
var body = document.getElementById("body");
if (nightButton.value = "night") {
body.classList.add("nightMode");
nightButton.value = "day";
localStorage.setItem('mode', 'nightMode');
} else {
body.classList.remove("nightMode");
nightButton.value = "night";
localStorage.setItem("mode", null);
}
};
.nightMode {
background-color: black;
color: white;
}
<body id="body">
<input type="button" value="night" id="nightButton">
<div>abcd</div>
</body>
Just change the line
if (nightButton.value = "night") {
to
if (nightButton.value == "night") {
You can simplify the mode button handler. This snippet including handling of localStorage (can't be used in SO-snippets) can be found #JsFiddle
document.addEventListener("click", evt => {
if (evt.target.id === "nightButton") {
const body = document.body;
body.classList.toggle("nightMode");
evt.target.value = `set ${
body.classList.contains("nightMode") ? "day" : "night"}`;
document.querySelector("#currentMode").textContent = `Current mode: ${
body.classList.contains("nightMode") ? "NIGHT" : "DAY"}`;
}
});
.nightMode {
background-color: black;
color: white;
}
body {
margin: 2rem;
}
#currentMode {
margin-top: 1rem;
}
<div>abcd
<input type="button" value="set night" id="nightButton">
</div>
<div id="currentMode"></div>
there is a little error in your code.
This code: if (nightButton.value = "night") {
Can you change it: if (nightButton.value == "night") {
Example here: https://codepen.io/yasgo/pen/OJRLErL
thank you all
I don't know if this is good codes but i tried this and it works ...
var mode = localStorage.getItem("mode");
document.getElementById("body").classList.add(mode);
if (mode == "nightMode") {
document.getElementById("nightButton").value = "day"
} else {
document.getElementById("nightButton").value = "night"
}
document.getElementById("nightButton").onclick = function () {
var nightButton = document.getElementById("nightButton")
var body = document.getElementById("body");
if (nightButton.value == "night") {
body.classList.add("nightMode");
nightButton.value = "day";
localStorage.setItem('mode', 'nightMode');
} else {
body.classList.remove("nightMode");
nightButton.value = "night";
localStorage.setItem("mode", "daymode");
}
};

How would you increase a variables value every second using a function?

I am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript.
// The variable we are trying to increase
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clicks += upgrade1;
document.getElementById("clicks").innerHTML = clicks;
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
autoClicker()
} else {
alert = "Sorry, you don't have enough clicks to buy this";
}
}
// The function I will use to increase clicks
function autoClicker() {}
You could create an AutoClicker class that has a start, pause, ad update function. It will be in charge of managing the setInterval id.
Edit: I updated it to include upgrade buttons and the target can now be manually clicked.
const upgrades = [{
cost: 50,
rate: 2
}, {
cost: 100,
rate: 4
}];
const main = () => {
const target = document.querySelector('.auto-clicker');
const span = document.querySelector('.info > span');
const btn = document.querySelector('.btn-toggle');
const clicker = new AutoClicker(target, 1000, (clicks) => {
span.textContent = clicks;
}).start();
initializeUpgrades(clicker, upgrades);
btn.addEventListener('click', (e) => {
e.target.textContent = clicker.isRunning() ? 'Start' : 'Pause';
clicker.toggle();
});
};
const initializeUpgrades = (clicker, upgrades) => {
const upgradeContainer = document.querySelector('.upgrades');
upgrades.forEach(upgrade => {
const btn = document.createElement('button');
btn.textContent = upgrade.cost;
btn.value = upgrade.rate;
btn.addEventListener('click', (e) => {
let cost = parseInt(e.target.textContent, 10);
let value = parseInt(e.target.value, 10);
if (clicker.clicks >= cost) {
clicker.clicks -= cost;
clicker.step = value
} else {
console.log(`Cannot afford the ${value} click upgrade, it costs ${cost} clicks`);
}
});
upgradeContainer.appendChild(btn);
});
};
class AutoClicker {
constructor(target, rate, callback) {
if (typeof target === 'string') {
target = document.querySelector(target);
}
this.target = target;
this.rate = rate;
this.callback = callback;
this.init();
}
init() {
this.step = 1;
this.clicks = 0;
this._loopId = null;
this.target.addEventListener('click', (e) => {
this.update();
});
}
isRunning() {
return this._loopId != null;
}
toggle() {
this.isRunning() ? this.pause() : this.start();
}
update() {
this.clicks += this.step;
if (this.callback) {
this.callback(this.clicks);
}
}
start() {
this.update(); // Update immediately
this._loopId = setInterval(() => this.update(), this.rate);
return this;
}
pause() {
clearInterval(this._loopId);
this._loopId = null;
return this;
}
}
main();
.wrapper {
width: 10em;
text-align: center;
border: thin solid grey;
padding: 0.5em;
}
.auto-clicker {
width: 4em;
height: 4em;
background: #F00;
border: none;
border-radius: 2em;
}
.auto-clicker:focus {
outline: none;
}
.auto-clicker:hover {
background: #F44;
cursor: pointer;
}
.info {
margin: 1em 0;
}
.upgrades {
display: inline-block;
}
.upgrades button {
margin-right: 0.25em;
}
<div class="wrapper">
<button class="auto-clicker"></button>
<div class="info">Clicks: <span class="clicks"></span></div>
<button class="btn-toggle">Pause</button>
<div class="upgrades"></div>
</div>
// The variable we are trying to increase
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clicks += upgrade1;
document.getElementById("clicks").innerHTML = clicks;
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
autoClicker()
} else {
alert = "Sorry, you don't have enough clicks to buy this";
}
}
// The function I will use to increase clicks
setInterval(function(){ clicks++;console.log(clicks); }, 1000);
Use setInterval to run a function at a specified interval. This will run increaseClicks every 1000 milliseconds (every second):
function increaseClicks() {
clicks++;
}
var interval = setInterval(increaseClicks, 1000);
Use clearInterval to stop running it:
clearInterval(interval);
You can omit var interval = if you don't want to use clearInterval:
setInterval(increaseClicks, 1000);
There might be several things to improve this code
the use of textContent is preferable to innerHTML, it checks if there are no html tags in the text
then using inline functions like ()=>{} are more useful but in this program it does'nt make a difference, where you to use it in object oriented context you could use it several ways
you don't need document.getElementById, you could just use id.
And finaly (this is just Γ  random tip which has nothing to do with much of anything) you may consider branchless programming because ifs are expensive.
Stackoverflow Branchless Programming Benefits
But anyways you should have fun :)
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clk.textContent = (clicks += upgrade1);
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
setInterval(()=>{getClicks();},1000);
} else {
alert("Sorry, you don't have enough clicks to buy this");
}
}
clk.onclick=()=>{getClicks();};
b.onclick=()=>{buyAutoClicker();};
html,body{height:100%;width:100%;margin:0;}
p{height:50px;width:50px;background:red;}
<p id="clk"></p>
<p id="b"></p>

Javascript code not running, how can I fix?

My code is supposed to add 1 to the counter when I hit space and then change the magnifying glass to tilt the other direction. It just doesn't do anything when I hit space.
I've fixed every problem I saw, nothing worked. Maybe somebody else knows, I'm really not that good at js.
var hits = 0;
var hitElement = document.querySelector( '.hits' );
document.body.onkeydown = function(e) {
if( e.keyCode == 32 ) {
addHit();
}
}
var mag = "πŸ”Ž";
var hitElement2 = document.querySelector( '.mag' );
document.body.onkeydown = function(f) {
if( f.keyCode == 32 ) {
if( mag.text == "πŸ”Ž") {
mag = "πŸ”";
renderMag();
else
mag = "πŸ”Ž";
renderMag();
}
}
}
var addHit = function() {
hits++;
renderHits();
}
var renderMag = function() {
hitElement2.innerHTML = mag;
}
var renderHits = function() {
hitElement.innerHTML = hits;
}
var resetHits = function() {
hits = 0;
renderHits();
}
Console says absolutely nothing too.
I fixed a few things and changed a few things that didn't need fixing. The three key points:
As mentioned, if a bit harshly, by Randy, your second event listener was overwriting your first, so hits was not increasing
The brackets in the if statement of your second event listener had some issues
Though checking the mag icon might work, using icons in the code feels like asking for something to break, so I changed that to a modulo check, to see whether hits was odd or even.
You were on the right track. When you have issues like this in the future, try putting console log statements in various places in the code. Make predictions about what variables should have what values at what points, then check if they do, then, if they don't, try to figure out why not.
var hits = 0;
var hitElement = document.querySelector('.hits');
var mag = "πŸ”Ž";
var hitElement2 = document.querySelector('.mag');
document.body.onkeydown = function(f) {
if (f.key == ' ') {
addHit();
if (hits % 2 === 0) {
mag = "πŸ”";
renderMag();
} else {
mag = "πŸ”Ž";
renderMag();
}
}
}
function addHit() {
hits++;
renderHits();
}
function renderMag() {
hitElement2.innerHTML = mag;
}
function renderHits() {
hitElement.innerHTML = hits;
}
function resetHits() {
hits = 0;
renderHits();
}
<div class="hits"></div>
<div class="mag"></div>

HTML + Javascript Button click again to undo

I was wondering how it is possible to make the button undo something too after clicking it. In my scenario just simple formatting of Text(Color,size etc), when you first click it, it formats the text as described in Javascript, but I would like to add a function, that when you click it again, that it undoes that.
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
I checked other articles already, which seemed to be related, but I did not get any smarter out of those, so my apologies in advance if it is a dup and thanks for your help!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
The easiest way to do this is to add and remove a class
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
Create an object that stores the initial values of your button and a variable which holds the state of it.
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
Now you can easily switch between the backup and the new values like this:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

Categories