Hello,
i searched around the web, but can't find right peace of codes..
I want to do:
- go to Fullscreen mode on a button click.
- change a background color to dark and save it as cookies.
Fullscreen mode:
i'm new with jQuery and can't find a right code. I found one, but when i click on button to next page, it turn's off the full screen mode to normal browser window, and changes my website background colors.
Founded code:
<html>
<head>
<title>TEST</title>
</head>
<body>
<img src="fullscreen.png">
<script>
function toggleFullScreen() {
if ((document.fullScreenElement && document.fullScreenElement !== null) ||
(!document.mozFullScreen && !document.webkitIsFullScreen)) {
if (document.documentElement.requestFullScreen) {
document.documentElement.requestFullScreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
</script>
</body>
</html>
Change Background and save as Cookies:
I want to do, that a members chooses on radio button's a theme White or Dark. The White theme default <div> background is white #fff(White). When member chooses the Dark theme, it changes <div> background to #000000(Black) color. I'm new and can't write a code, without examples or something. Can someone tell me, how can i do it with Cookies and Javascript/jQuery?
Members settings page to change it:
<html>
<head>
<title>Settings</title>
</head>
<body>
<p>Change Theme</p>
<form>
<input type="radio" id="Light" title="White Theme">
<br />
<input type="radio" id="Dark" title="Dark theme">
<br />
<input type="submit" id="submit" value="Submit">
</form>
</body>
</html>
Page BEFORE changes the Theme to Dark:
<html>
<head>
<title>Home Page</title>
</head>
<body>
<div style="background:#fff;height:600px;width:100%;">
<!-- SOME CONTENT -->
</div>
</body>
</html>
and Page AFTER changes the Theme to Dark:
<html>
<head>
<title>Home Page</title>
</head>
<body>
<div style="background:#000000;height:600px;width:100%;">
<!-- SOME CONTENT -->
</div>
</body>
</html>
Thanks!
You can set a cookie value, like this:
document.cookie = "theme=black";
Or, if you want to keep other settings, then:
function changeCookieValue(attribute, value) {
var previousCookie = document.cookie.split(";");
for (var i = 0; i < previousCookie.length; i++) {
var key = previousCookie[i].substring(0,previousCookie[i].indexOf("="));
if (key === attribute) {
previousCookie[i] = attribute + "=" + value;
document.cookie = previousCookie.join(";");
return;
}
}
document.cookie = document.cookie + ";" + attribute + "=" + value;
}
And you can use it like this:
`changeCookieValue("black");`
This is how you can read from cookie:
function getCookieValue(attribute) {
var previousCookie = document.cookie.split(";");
for (var i = 0; i < previousCookie.length; i++) {
var key = previousCookie[i].substring(0,previousCookie[i].indexOf("="));
if (key === attribute) {
return presiousCookie[i].substring(previousCookie[i].indexOf("=") + 1);
}
}
return "";
}
You can set the class of the body, like this:
$("body").addClass(getCookieValue("theme"));
just make sure that body is already loaded when you run this part. You can design the themes like this:
.black > div {
background: #000000;
}
.white > div {
background: #fff;
}
Alternatively, you can work with localStorage, which is much more handy. As about full screen mode, there is no reason to reinvent the wheel, since there is a good fullscreen API you should use for this purpose.
And you can make sure that changeCookieValue runs with the proper parameter on click using the onclick attribute of your radio buttons.
Alternatively, you might consider storing the values inside a database and adding the needed class to body on server, when you generate it.
EDIT:
You can add the class at the loaded event:
$(function() {
$("body").addClass(getCookieValue("theme"));
});
Note, that this will be responsible to display the theme at page load. You need to display it whenever you call changeCookieValue for theme. Before you call that function $("body").removeClass(getCookieValue("theme")); and after the function is executed $("body").addClass(getCookieValue("theme")); (note, that the theme is changed). Naturally, you need a wrapper for this:
function changeTheme(theme) {
$("body").removeClass(getCookieValue("theme"));
changeCookieValue("theme", theme);
$("body").addClass(getCookieValue("theme"));
}
and trigger this changeTheme at your radio buttons.
Related
i am trying to make the element with ID thanks1 disappear after a set amount of time. So far I have tried many things like setTimeout but none have worked
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script src="scripts.js"> </script>
</head>
<body>
<h1> 1 </h1>
<p> QUESTION </p>
<button onclick="rightAnswer()" id="a"> PLACE HOLDER </button>
<button onclick="wrongAnswer()"> PLACE HOLDER </button>
<p id="output"> </p>
<p id="thanks1"> Well Done </p>
</body>
</html>
This is a quiz and it gets you to the next page when you get a question correct, I tried putting a timeout in the rightAnswer function so as soon as you load 1.html the Well Done disappears after some time.
const wrong = "Wrong, try again!";
function wrongAnswer() {
document.getElementById('output').innerHTML = wrong
}
function rightAnswer() {
if (document.getElementById('a')) {
location.href = "1.html";
setTimeout(document.getElementById('thanks1').style.display = "none", 3000)
}
if (document.getElementById('b')) {
location.href = "2.html"
}
if (document.getElementById('c')) {
location.href = "3.html"
}
}
function goBack() {
if (document.getElementById('b')) {
location.href = "index.html"
}
if (document.getElementById('c')) {
location.href = "1.html"
}
if (document.getElementById('d')) {
location.href = "2.html"
}
}
I wanted to make the element with the ID "thanks1" disappear once its corresponding page has loaded and after a set amount of time. I tried using setTimeout but nothing that I wanted seemed to happen.
Your syntax is incorrect.
MDN Docs: setTimeout()
From the docs:
The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
setTimeout(functionRef, delay)
// Parameters
// functionRef - A **function** to be executed after the timer expires.
// delay - The time, in milliseconds that the timer should wait before
// the specified function or code is executed.
For simplicity, I used the same 'thanks1' container for outputting the values
function wrongAnswer() {
// "wrong" should be a string unless you're calling a variable
document.getElementById('thanks1').innerHTML = "wrong";
}
function rightAnswer() {
if (document.getElementById('a')) {
location.href = "1.html";
setTimeout(wrongAnswer, 3000)
}
...
}
Example:
https://codepen.io/carbonspace/pen/QWxwvRo
I have the following code on my website where I am trying to set light or dark mode based on the settings of the users system/browser as well as the ability to change the setting based on a button press.
What I want to happen is:
It is daytime orthe users browser is set to light. The website loads the light.css and the button shows the moon icon to switch to the light theme.
It is night time or the user has their theme set to dark mode. The website loads the dark.css theme and the icon in the button switches to the sun.
Perhaps I am missing something here to get it all functioning correctly? Mainly the buttons do not switch.
function lightDark() {
var el = document.querySelectorAll(".light, .dark")
if (el.href.match("light.css")) {
el.href = "dark.css";
} else {
el.href = "light.css";
}
}
<
script type = "text/javascript" >
$('#lightDarkToggle').click(function() {
if (window.matchMedia('prefers-color-scheme: dark').matches) {
$(this).find('i').toggleClass('fa-sun'),
el.href = "dark.css";
} else {
$(this).find('i').toggleClass('fa-moon'),
el.href = "light.css";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link class="light" rel="stylesheet" href="light.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)" />
<link class="dark" rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)" />
<button id="lightDarkToggle" onclick="lightDark()"><i class="fas fa-moon"></i></button>
I think this line var el = document.querySelectorAll("#light, #dark")
should be var el = document.querySelectorAll(".light, .dark"), because your link tags have a class, not an id.
Another thing, in your second script tag, you try to update el.href, but in this function, el is never defined. It has been defined in another function (lightDark()), so it is not accessible anymore at the end of it.
I have a function that sets the color theme of my site when clicked, but when I reload the page or go to a new page, it reverts back to the default theme. There's a line of my code that is supposed to get the previous theme from localStorage and apply it to the new one, but I think why it isn't working is that there isn't actually any code that saves the theme to Storage. Either that, or localStorage resets when the page is reloaded/changed. Either way, I'm not sure how to fix it.
This is my code:
<a class="switch-light-purple color-palette" id="color-palette" onclick="setTheme('theme-light-purple')">
<script>
// function to set a given theme/color-scheme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// Immediately invoked function to set the theme on initial load
(function () {
if (localStorage.getItem('theme') === 'theme-light-purple') {
setTheme('theme-light-purple');
}
})();
</script>
</a>
<a class="switch-dark-blue color-palette" id="color-palette" onclick="setTheme('theme-dark-blue')">
<script>
// function to set a given theme/color-scheme
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
// Immediately invoked function to set the theme on initial load
(function () {
if (localStorage.getItem('theme') === 'theme-dark-blue') {
setTheme('theme-dark-blue');
}
})();
</script>
</a>
Separation of concerns:
Keep your html, css, and js in their respective files ALWAYS, there's no substitution for this.
So your index.html should look something like this (assuming index.html, style.css, and main.js are all in the same folder).
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="parent-container">
<a data-theme="theme-dark-blue" class="switch-dark-blue color-palette" id="color-palette">Dark Blue </a>
<a data-theme="theme-light-purple" class="switch-light-purple color-palette" id="color-palette2">Light Purple</a>
</div>
<script src="main.js"></script>
</body>
</html>
Your CSS will be in a file called style.css,
And your JS,
// This waits for the DOM to complete loading
document.addEventListener('DOMContentLoaded', function() {
// all your code goes inside this.
});
Also, as #Sebastian Simon pointed out in the comments,
Repeating the same id is invalid in HTML. Inline event handlers like onclick are not recommended. They are an obsolete, hard-to-maintain and unintuitive way of registering events. Always use addEventListener instead.
Unique IDs:
You could change the id of one of your anchor tags to color-palette2 for instance, but since you have a lot of different themes you could pick names that are more self-explanatory. But, as long as your ids are unique (1 unique id per page), it's fine.
Event Listeners:
Use .addEventListener to add events to your DOM nodes. I've done this in the code snippet I've shared. It's very easy once you get used to it.
I've also used data attributes to pass your theme in a more "dynamic" way to your logic. StackOverflow snippets don't support localStorage hence I've commented that line out.
function setTheme() {
let theme;
let savedTheme = localStorage.getItem('theme')
// check if localstorage already has a theme defined
// if it has, then set theme variable to it
// otherwise, get the theme from the data-theme attribute
// of the current anchor tag clicked represented by this.
theme = savedTheme || this.dataset.theme
let div = document.querySelector('div.parent-container')
// I'm adding this to a div
// you can add it to the body tag.
div.classList.add(theme)
// this code can be better but the idea is
// to remove all other themes and keep only the intended one.
if (theme === 'theme-dark-blue') {
div.classList.remove('theme-light-purple')
} else {
div.classList.remove('theme-dark-blue')
}
console.log(`Set theme to ${theme}`)
}
let palettes = document.querySelectorAll('.color-palette')
palettes.forEach(function(p) {
p.addEventListener('click', setTheme)
})
a {
cursor: pointer;
text-decoration: underline;
color: blue;
}
.switch-light-purple {
color: purple;
margin: 0 15px;
}
<div class="parent-container">
<a data-theme="theme-dark-blue" class="switch-dark-blue color-palette" id="color-palette">Dark Blue </a>
<a data-theme="theme-light-purple" class="switch-light-purple color-palette" id="color-palette2">Light Purple</a>
</div>
PS: the code snippet won't work since StackOverflow does not support localStorage.
I want to save the user preferred theme (light/dark) in cookies. Can someone help me with it? I'm really bad at JS. I submit my current script.
Stylesheets:
<link rel="stylesheet" href="custom.css" id="pagestyle2" type="text/css" charset="utf-8"/>
<link href="file-upload.css" id="pagestyle4" rel="stylesheet">
<link href="bootstrap.css" id="pagestyle3" rel="stylesheet">
<link href="hg.css" id="pagestyle" rel="stylesheet">
Switcher:
<li class="nav-item" id="pagestylechoose">
</li>
Switcher JS:
function swapStyleSheet(sheet) {
document.getElementById('pagestyle').setAttribute('href', sheet);
}
function swapStyleSheet2(sheet) {
document.getElementById('pagestyle2').setAttribute('href', sheet);
}
function swapStyleSheet3(sheet) {
document.getElementById('pagestyle3').setAttribute('href', sheet);
}
function swapStyleSheet4(sheet) {
document.getElementById('pagestyle4').setAttribute('href', sheet);
}
Although it requires a little modification of your CSS, there is another solution instead of having to load different style sheets.
Load a default version, for this example, lets say its the light version. Then when the visitor wants the dark version, a class is added to the BODY called dark.
Then within your DARK version of the CSS, just add body.dark to the beginning of all CSS selectors.
Fiddle: https://jsfiddle.net/Lw7461ey/ (SO Snippets blocks localstorage so I used jsfiddle)
This way you can load all of the CSS files at once, you can even compress them if you wanted to.
var ChangeTheme = document.querySelector(".ChangeTheme");
if(localStorage.getItem("theme") === undefined){
localStorage.setItem("theme","light");
}
function setTheme(){
document.body.classList.remove("dark");
document.body.classList.remove("light");
document.body.classList.add(localStorage.getItem("theme"));
}
ChangeTheme.addEventListener("click",function(){
localStorage.setItem("theme",(localStorage.getItem("theme") === "dark") ? "light" : "dark");
setTheme();
});
setTheme();
For your CSS for example
Lets say in light you have:
a{color:#000000;}
For dark, just change it to:
body.dark a{color:#ffffff;}
I would suggest you have a single function that get called when the button is clicked, specially that the stylesheet names are hard coded anyways
<li class="nav-item" id="pagestylechoose">
</li>
..
function changeStyleToDark() {
document.cookie += "style=dark";
swapStyleSheet('dark.css');
swapStyleSheet2('custom-dark.css');
swapStyleSheet3('bootstrap-dark.css');
swapStyleSheet4('file-upload-dark.css');
}
function swapStyleSheet(sheet) {
document.getElementById('pagestyle').setAttribute('href', sheet);
}
function swapStyleSheet2(sheet) {
document.getElementById('pagestyle2').setAttribute('href', sheet);
}
function swapStyleSheet3(sheet) {
document.getElementById('pagestyle3').setAttribute('href', sheet);
}
function swapStyleSheet4(sheet) {
document.getElementById('pagestyle4').setAttribute('href', sheet);
}
Now to get the read the user style later you can use
function getUserStyle() {
return getCookieByName("style");
}
function getCookieByName(cookieName) {
var cookieString = RegExp(cookieName + "=[^;]+").exec(document.cookie);
return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
}
Now, on the beginning of the script, and whenever the page loads, check for the cookie and call changeStyleToDark if it's set to dark.
window.onload = (event) => {
if (getUserStyle() === "dark") changeStyleToDark();
};
I am trying to do an onclick event where when a light bulb image is clicked it goes from a light bulb off to a light bulb on image and vice versa.
I am using an external javascript file. when I click on the image nothing happens.
I cant figure out whats wrong,
my html portion:
<head>
<link rel="stylesheet" href="css/program-01.css" />
<script type="text/javascript" src="javascript/program-01.js"></script>
<title>
<h1>Program-01</h1>
</title>
</head>
<body>
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulbFunction()" />
</div>
</body>
my js file function:
function LightBulb() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change = "images/light_on.png";
} else {
image_change = "images/light_off.png";
}
}
Suggestions/Problems:
You function names are different.
You're using the function LightBulbFunction on the onclick event. But, you don't have the function of that name in your script. You'll get
ReferenceError: LightBulbFunction() is not defined.
To change the image src attribute value, use image_change.src inside the event handler.
To solve the problem change the name of onclick attribute value to LightBulb.
function LightBulb() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change.src = "images/light_on.png";
// ^^^^
} else {
image_change.src = "images/light_off.png";
// ^^^^
}
}
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" />
<!-- ^^^^^^^^^^^ -->
</div>
Better approach will be to use addEventListener to bind events on the elements.
document.getElementById('light_off').addEventListener('click', function() {
var image_change = document.getElementById("light_off");
if (image_change.src == "images/light_off.png") {
image_change.src = "images/light_on.png";
} else {
image_change.src = "images/light_off.png";
}
}, false);
<div id="LightOff">
<img src="images/light_off.png" id="light_off" alt="" onclick="LightBulb()" />
<!-- ^^^^^^^^^^^ -->
</div>
Well in your html, the code is onclick="LightBulbFunction()" while in javascript it is LightBulb. Change either of them and make them match
You are not redefining the .src. Change
image_change =
to
image_change.src =
And your function needs to have the same LightBulb function name.