I can't combine 2 javascript files into 1 - javascript

I have 2 javascript files and I want to combine them. One is for dark-mode and the other one is for dark-mode switch button. Separately they work fine, but when combined dark-mode works like it should, but switch button place isn't saved after refreshing the page. What can I do to fix that?
/* DARK-MODE */
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
(function() {
let onpageLoad = localStorage.getItem("theme") || "";
let element = document.body;
element.classList.add(onpageLoad);
document.getElementById("theme").textContent = "DarkMode";
localStorage.getItem("theme") || "light";
})();
function themeToggle() {
let element = document.body;
element.classList.toggle("dark-mode");
let theme = localStorage.getItem("theme");
if (theme && theme === "dark-mode") {
localStorage.setItem("theme", "");
} else {
localStorage.setItem("theme", "dark-mode");
}
document.getElementById("theme").textContent = localStorage.getItem("theme");
};
/* DM-BUTTON */
function App() {}
App.prototype.setState = function(state) {
localStorage.setItem('checked', state);
}
App.prototype.getState = function() {
return localStorage.getItem('checked');
}
function init() {
var app = new App();
var state = app.getState();
var checkbox = document.querySelector('#toggle');
if (state == 'true') {
checkbox.checked = true;
}
checkbox.addEventListener('click', function() {
app.setState(checkbox.checked);
});
}
init();
<div class="toggle1">
<input type="checkbox" onclick="themeToggle()" class="dmbtn" id="toggle">
<label for="toggle"></label>
</div>

Related

In Swashbuckle / Swagger; How do I hide a dropdown menu based on anothers selected value

I'm struggeling with this functionality of hiding a row based on a select:
<tr data-param-name="nodeGroup">
in web api, Program.cs:
app.UseSwaggerUI(options => {
options.InjectJavascript("/custom.js");
});
The javascript custom.js:
var providerSelect = null;
var nodeGroup = null;
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
// document ready
providerSelect = document.querySelector("[data-param-name='provider'] select");
nodeGroup = document.querySelector("[data-param-name='nodeGroup']");
if (providerSelect) {
providerSelect.addEventListener("change", function () {
var text = providerSelect.options[providerSelect.selectedIndex].text;
if (text == "EcoPlatform") {
nodeGroup.setAttribute("visibility", "visible");
}
else {
nodeGroup.setAttribute("visibility", "collapse");
}
});
}
}
};
The above does not work.
The page is not actually shown on readystate === 'complete'
providerSelect does not get populated before I click the downarrow on the "accordion". <noscript> is replaced on click.
Was solved like this:
document.addEventListener("change", function (event) {
var providerSelect = document.querySelector("[data-param-name='provider'] select");
if (event.target == providerSelect) {
var nodeGroup = document.querySelector("[data-param-name='nodeGroup']");
var selectedText = providerSelect.options[providerSelect.selectedIndex].text;
var dataset = document.querySelector("[data-param-name='datasetType']");
if (selectedText == "EcoPlatform") {
nodeGroup.style["visibility"] = "visible";
dataset.style["visibility"] = "visible";
}
else {
nodeGroup.style["visibility"] = "collapse";
dataset.style["visibility"] = "collapse";
}
}
});

Local storage not working properly for JS onclick

My local storage works in terms of saying true and false, but when the page is refreshed, it reverts but keeps the value. For example, if I switch from default darkmode (false) to lightmode (true), it shows as true in the local storage (which is good). However, when I refresh the page, although the value still is true, the page has reverted to its default (false).
HTML:
<body onload="stored()">
<label for="ID_HERE" class="toggle-switchy">
<input checked type="checkbox" name="server" id="ID_HERE" />
<span class="toggle" onclick="toggle()" id="saveDarkLight"></span>
<span class="switch"></span>
</label>
</body>
JS:
function stored() {
var storedValue = localStorage.getItem("server");
if (storedValue) {
lightmode()
document.getElementById("ID_HERE").checked = true;
} else {
darkmode()
document.getElementById("ID_HERE").checked = false;
}
}
function toggle() {
if (document.getElementById("ID_HERE").checked) {
lightmode()
var input = document.getElementById("ID_HERE");
localStorage.setItem("server", input.checked);
}
else {
darkmode()
var input = document.getElementById("ID_HERE");
localStorage.setItem("server", input.checked);
}
}
function darkmode() {
const bodyChanges = document.querySelectorAll('.margin_body');
for (let i = 0; i < bodyChanges.length; i++) {
bodyChanges[i].style.background = '#0c0a0f';
}
}
function lightmode() {
const bodyChanges = document.querySelectorAll('.margin_body');
for (let i = 0; i < bodyChanges.length; i++) {
bodyChanges[i].style.background = 'white';
}
}
localStorage only saves string values, so saving true or false will convert it to 'true' or 'false'.
When you read back, you need to either JSON.parse it or check against the string values.
function stored() {
const storedValue = localStorage.getItem("server");
if(storedValue === 'true'){ // <------
lightmode()
document.getElementById("ID_HERE").checked = true;
}else{
darkmode()
document.getElementById("ID_HERE").checked = false;
}
}
First and foremost, I think you'll want the onclick event handler on the input element.
Also, the following is a quick and dirty implementation:
JS:
const SAVED_USER_INPUT = "savedUserInput";
const TARGET_ID = "toggle-text";
const BLUE = "blue";
const RED = "red";
const text = {
[BLUE]:
"Text color currently set to blue (default/unchecked state). Click to change to red",
[RED]: "Text color currently set to red. Click to change to blue",
};
const handleToggle = (event) => {
const isChecked = event.target.checked;
const color = isChecked ? RED : BLUE;
setColor(color);
setText(color);
savePreference(color);
};
const setColor = (fontColor = BLUE) => {
document.getElementById(TARGET_ID).style.color = fontColor;
return true;
};
const setText = (color) => {
document.getElementById(TARGET_ID).innerText = text[color];
return true;
};
const setChecked = (color) => {
if (color === RED) {
document.getElementsByTagName("input")[0].setAttribute("checked", true);
}
};
const savePreference = (color) => localStorage.setItem(SAVED_USER_INPUT, color);
const getSavedPreference = () => localStorage.getItem(SAVED_USER_INPUT);
// localStorage.clear()
window.onload = () => {
if (!(getSavedPreference() === null)) {
const savedColor = getSavedPreference();
setColor(savedColor);
setText(savedColor);
setChecked(savedColor);
} else {
setColor();
setText(BLUE);
setChecked(BLUE);
}
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title>localStorage</title>
<script src="app.js"></script>
</head>
<body>
<label>
<input type="checkbox" onclick="handleToggle(event)">
<span id="toggle-text"></span>
</span>
</label>
</body>
</html>

My localStorage value is not working the way I intend, why is that?

The darkmode toggling works the way I want to, but when I refresh the page when I'm on the darkmode the value goes "out of sync" so to speak and I don't know why. Here is my code:
var state;
state = 1;
function store() {
localStorage.getItem("state");
if(state==0 || state == undefined){
state = 1;
localStorage.setItem("state", 1);
}
else if (state==1){
state = 0;
localStorage.setItem("state", 0);
}
localStorage.setItem("state", state);
}
function check(){
x = localStorage.getItem("state");
if(x==0){
var element = document.body;
element.classList.toggle("darkMode");
}
else if(x==null){
alert("Your browser or its settings don't work with localStorage");
}
}
function change(){
var element = document.body;
element.classList.toggle("darkMode");
var elem = document.getElementById("button");
if (elem.innerHTML=="Dark mode"){
elem.innerHTML = "Light mode";
}
else{
elem.innerHTML = "Dark mode";
}
}
window.onload = check;

Keep web changes after refreshing

I just added a dark mode and currency switcher using JS, but the changes don't save after refreshing the page. Does somebody know how to use localStorage on the following codes? Changes can be seen on the following website Morocco tours.
Dark theme:
var icon = document.getElementById("icon-phone");
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}
var icon = document.getElementById("icon");
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}
You can use localStorage.setItem('key', 'value') to set and localStorage.getItem('key') to read a localStorage item.
You could, for example, set localStorage.setItem('dark-theme', true) and later retrieve it with localStorage.getItem('dark-theme').
var isDarkTheme = window.localStorage.getItem('dark-theme');
if (isDarkTheme === null) {
isDarkTheme = false;
} else {
isDarkTheme = isDarkTheme === 'true'
}
var icon = document.getElementById("icon-phone");
if (isDarkTheme) {
document.body.classList.add('dark-theme')
}
icon.onclick = function () {
isDarkTheme = !isDarkTheme;
if (isDarkTheme) {
document.body.classList.add('dark-theme');
} else {
document.body.classList.remove('dark-theme');
}
window.localStorage.setItem('dark-theme', isDarkTheme);
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}

Self made text-to-speech in javascript doesn't work properly

We made a text-to-speech function in javascript. The only problem now is that it doesn't work properly. When the play button is pressed, it is supposed to tell everything that's within the body tags. The problem is that most of the times it's not working and when it does, it's telling also the javascript code which it's outside of the body tag. How can i fix this so that it's working everytime the play button is pressed and it's only telling everything in the body tag?
onload = function() {
if ('speechSynthesis' in window) with(speechSynthesis) {
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if (!flag) {
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('body').textContent);
utterance.lang = 'nl-NL';
utterance.rate = 0.7;
utterance.onend = function() {
flag = false;
playEle.className = pauseEle.className = '';
stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) {
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if (speaking && !paused) {
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if (speaking) {
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
<button id=play>Play</button>
<button id=pause>Pause</button>
<button id=stop>Stop</button>
Define the DIV you want the Speech recognition to read from:
</head>
<body>
<div>
<button id=play>Play</button>
<button id=pause>Pause</button>
<button id=stop>Stop</button>
</div>
<div id="readFrom">
Just a test o my friend mplungjan
</div>
<script type="text/javascript">
window.onload = function () {
if ('speechSynthesis' in window)
with (speechSynthesis) {
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if (!flag) {
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('#readFrom').innerHTML);
utterance.lang = 'nl-NL';
utterance.rate = 0.7;
utterance.onend = function () {
flag = false;
playEle.className = pauseEle.className = '';
stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) {
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if (speaking && !paused) {
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if (speaking) {
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
</script>
</body>
It should be very simple. I see on your line that you are querying all the body text Content but that should not be it. Go on your JS Console and query: document.querySelector('body').textContent
You should see exactly what you are passing as arguments to:
utterance = new SpeechSynthesisUtterance(document.querySelector('body').textContent);
So now it's up to you, you would have to filter what you want to be read by putting it in a specific DIV or stripping HTML from the page according to a complex logic keeping just what you want to read.

Categories

Resources