I want to save checkbox state when page reload.
This is my code for get checkbox state:
jQuery(document).ready(function(){
jQuery("#advanced_menu_switch").on("click",function(){
if(jQuery(this).is(":checked")) {
jQuery("#menu-posts-cms_block").addClass("active");
jQuery("#menu-posts-portfolio").addClass("active");
jQuery("#menu-posts-woodmart_size_guide").addClass("active");
jQuery("#menu-posts-woodmart_slide").addClass("active");
}
else{
jQuery("#menu-posts-cms_block").removeClass("active");
jQuery("#menu-posts-cms_block").removeClass("active");
jQuery("#menu-posts-portfolio").removeClass("active");
jQuery("#menu-posts-woodmart_size_guide").removeClass("active");
jQuery("#menu-posts-woodmart_slide").removeClass("active");
}
}
);})
#adminmenu li.menu-top.menu-top-first a:hover,
#adminmenu li.menu-top.menu-top-first:hover{
color: inherit !important;
background-color: inherit !important;
}
.switch {
position: relative;
display: inline-block;
width: 70px;
height: 28px;
margin-top: 5px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(42px);
-ms-transform: translateX(42px);
transform: translateX(42px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
li.active{
display:none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch">
<input type="checkbox" id="advanced_menu_switch">
<span class="slider"></span>
</label>
<li id="menu-posts-cms_block">menu-posts-cms_block</li>
<li id="menu-posts-portfolio">menu-posts-portfolio</li>
<li id="menu-posts-woodmart_size_guide">menu-posts-woodmart_size_guide</li>
<li id="menu-posts-woodmart_slide">menu-posts-woodmart_slide</li>
Now, i want to save the checkbox state when page reload. This is my code:
var checkbox = document.getElementById("advanced_menu_switch");
localStorage.setItem("advanced_menu_switch", checkbox.checked);
//for loading
var checked = JSON.parse(localStorage.getItem("advanced_menu_switch"));
document.getElementById("advanced_menu_switch").checked = checked;
I put this piece of code to save the state of the checkbox at the end of the function, but it doesn't work
Perhaps this idea of saving the state of the checkbox can be rewritten in another way.
Any one can help me
There are multiple ways to save the check box state on page load but I have used a trigger method of jQuery so please find below the solution
jQuery(document).ready(function () {
jQuery("#advanced_menu_switch").on("change", function (e) {
if (jQuery(this).is(":checked")) {
jQuery("#menu-posts-cms_block").addClass("active");
jQuery("#menu-posts-portfolio").addClass("active");
jQuery("#menu-posts-woodmart_size_guide").addClass("active");
jQuery("#menu-posts-woodmart_slide").addClass("active");
// Store value in local storage.
localStorage.setItem("advanced_menu_switch", this.checked);
}else {
jQuery("#menu-posts-cms_block").removeClass("active");
jQuery("#menu-posts-cms_block").removeClass("active");
jQuery("#menu-posts-portfolio").removeClass("active");
jQuery("#menu-posts-woodmart_size_guide").removeClass("active");
jQuery("#menu-posts-woodmart_slide").removeClass("active");
// Remove item in local storage.
localStorage.removeItem("advanced_menu_switch");
}
});
// Checked checkbox value if value exist in local storage.
setTimeout(function () {
var checked = localStorage.getItem("advanced_menu_switch");
if (checked == 'true') {
jQuery("#advanced_menu_switch").prop("checked", true).trigger("change");
}}, 0);
});
And here you can check trigger event for checkbox
Related
I got a toggle that switches between dark mode and light mode:
<div class="dark-mode-toggler">
<input type="checkbox" id="dark-mode-toggler"/>
<label for="dark-mode-toggler" aria-label="Toggler for Dark Mode"></label>
</div>
Then I got a script that switches to dark mode when the toggle switch is clicked:
<script>
// check for saved 'darkMode' and 'darkModeToggle' in localStorage
let darkMode = localStorage.getItem('darkMode');
const darkModeToggle = document.querySelector('#dark-mode-toggler');
const enableDarkMode = () => {
// 1. Add the class to the body
document.body.classList.add('darkmode');
// 2. Update darkMode in localStorage
localStorage.setItem('darkMode', 'enabled');
}
const disableDarkMode = () => {
// 1. Remove the class from the body
document.body.classList.remove('darkmode');
// 2. Update darkMode and toggle in localStorage
localStorage.setItem('darkMode', null);
}
// If the user already visited and enabled darkMode
// start things off with it on
if (darkMode === 'enabled') {
enableDarkMode();
}
// When someone clicks the button
darkModeToggle.addEventListener('click', () => {
// get their darkMode setting
darkMode = localStorage.getItem('darkMode');
// if it not current enabled, enable it
if (darkMode !== 'enabled') {
enableDarkMode();
// if it has been enabled, turn it off
} else {
disableDarkMode();
}
});
</script>
But when I refresh or switch page, the toggle switch is reset.
How can we use localStorage to save the toggle switch status and load the current status when switching or refreshing pages?
Here is my CSS for completeness
.dark-mode-toggler {
position: fixed;
top: 5px;
right: 20px;
}
.dark-mode-toggler label {
position: relative;
}
.dark-mode-toggler input[type='checkbox'] {
display: none;
}
.dark-mode-toggler input[type='checkbox'] + label::before {
content: '';
display: block;
height: 26px;
width: 60px;
background: #fff;
border: 2px solid #96979c;
border-radius: 15px;
position: absolute;
top: 0px;
left: -65px;
}
.dark-mode-toggler input[type='checkbox'] + label::after {
content: '';
display: block;
height: 20px;
width: 20px;
background: #96979c;
border: 2px solid #fff;
border-radius: 50%;
position: absolute;
top: 3px;
left: -62px;
transition: all 0.4s ease-in;
}
.dark-mode-toggler input[type='checkbox']:checked + label::before {
background: #000;
border: 2px solid #fff;
}
.dark-mode-toggler input[type='checkbox']:checked + label::after {
left: -28px;
background: #000;
border: 2px solid #fff;
transition: all 0.4s ease-in;
}
:root {
--clr-light: transparent;
--clr-dark: #00332a;
--clr-primary: #dbffa2;
--clr-secondary: #c3fcf2;
--clr-accent: #ff7750;
--foreground: var(--clr-dark);
--background: var(--clr-light);
}
.darkmode {
--clr-light: #fdffc4;
--clr-dark: #00332a;
--clr-primary: #202302;
--clr-secondary: #00100d;
--clr-accent: #ff7750;
--foreground: var(--clr-light);
--background: var(--clr-dark);
}
body {
background: var(--background);
color: var(--foreground);
}
The problem is that you don't set the initial state of the checkbox on page reload. You'll need to set the checked attribute of the checkbox on page refresh to show that the mode is enabled.
const enableDarkMode = () => {
// 1. Add the class to the body
document.body.classList.add('darkmode');
// 2. Update darkMode in localStorage
localStorage.setItem('darkMode', 'enabled');
// 3. toggle the checkbox
darkModeToggle.setAttribute('checked', true);
}
I have added a button on my site which let's the users change to dark or light mode whenever they want. I added the button with a moon icon on it, but the problem is that I want that the moon icon changes to sun icon when the user is in dark mode. And changes to moon icon when user is in light mode.
function myfunction(e) {
console.log("you clicked");
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
<button class="btn"><img src='moon.png'></img></button>
The .inverted class in js is because I don't want the images to invert their colors.. so I gave all the images a class='inverted'
So, this is what I've done and someone please let me know how I should change the icon to moon and sun depending on the current mode (light or dark)
Thanks!
You could add the sun as another image to the button and change the visibility of the two images via your .dark-mode css class.
So whenever the .dark-mode class is present the moon gets hidden and the sun gets shown.
function myfunction(e) {
console.log("you clicked");
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
/* button handling */
.moon {
display: block;
}
.sun {
display: none;
}
.dark-mode .moon {
display: none;
}
.dark-mode .sun {
display: block;
}
<button class="btn">
<img class="moon" src="moon.png" alt="moon"></img>
<img class="sun" src="sun.png" alt="sun"></img>
</button>
You could go with the CSS approach as in #Fabian's answer. If you would like to go with JS, you could simply use a flag to indicate whether or not the user switched to dark mode, and dynamically set the icon based on it.
let isDarkMode = document.documentElement.classList.contains("dark-mode");
function myfunction(e) {
document.documentElement.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
e.currentTarget.querySelector("img").src = isDarkMode ? "sun.png" : "moon.png";
}
You can use the below reference for the toggle button from light mode to dark mode and dark mode to light mode.
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.toggle-checkbox {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
.toggle-slot {
position: relative;
height: 10em;
width: 20em;
border: 5px solid #e4e7ec;
border-radius: 10em;
background-color: white;
box-shadow: 0px 10px 25px #e4e7ec;
transition: background-color 250ms;
}
.toggle-checkbox:checked ~ .toggle-slot {
background-color: #374151;
}
.toggle-button {
transform: translate(11.75em, 1.75em);
position: absolute;
height: 6.5em;
width: 6.5em;
border-radius: 50%;
background-color: #ffeccf;
box-shadow: inset 0px 0px 0px 0.75em #ffbb52;
transition: background-color 250ms, border-color 250ms, transform 500ms cubic-bezier(.26,2,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .toggle-button {
background-color: #485367;
box-shadow: inset 0px 0px 0px 0.75em white;
transform: translate(1.75em, 1.75em);
}
.sun-icon {
position: absolute;
height: 6em;
width: 6em;
color: #ffbb52;
}
.sun-icon-wrapper {
position: absolute;
height: 6em;
width: 6em;
opacity: 1;
transform: translate(2em, 2em) rotate(15deg);
transform-origin: 50% 50%;
transition: opacity 150ms, transform 500ms cubic-bezier(.26,2,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .sun-icon-wrapper {
opacity: 0;
transform: translate(3em, 2em) rotate(0deg);
}
.moon-icon {
position: absolute;
height: 6em;
width: 6em;
color: white;
}
.moon-icon-wrapper {
position: absolute;
height: 6em;
width: 6em;
opacity: 0;
transform: translate(11em, 2em) rotate(0deg);
transform-origin: 50% 50%;
transition: opacity 150ms, transform 500ms cubic-bezier(.26,2.5,.46,.71);
}
.toggle-checkbox:checked ~ .toggle-slot .moon-icon-wrapper {
opacity: 1;
transform: translate(12em, 2em) rotate(-15deg);
}
<head>
<script src="https://code.iconify.design/1/1.0.4/iconify.min.js"> </script>
</head>
<label>
<input class='toggle-checkbox' type='checkbox'>
<div class='toggle-slot'>
<div class='sun-icon-wrapper'>
<div class="iconify sun-icon" data-icon="feather-sun" data-inline="false"></div>
</div>
<div class='toggle-button'></div>
<div class='moon-icon-wrapper'>
<div class="iconify moon-icon" data-icon="feather-moon" data-inline="false"></div>
</div>
</div>
</label>
function myfunction(e) {
const doc = document.documentElement
doc.classList.toggle("dark-mode");
document.querySelectorAll(".inverted").forEach((result) => {
result.classList.toggle("invert");
});
const img = e.currentTarget.querySelector('img')
const label = e.currentTarget.querySelector('span')
if (doc.classList.contains('dark-mode')) {
img.src = 'sun.png'
label.innerHTML = 'Light mode'
} else {
img.src = 'moon.png'
label.innerHTML = 'Dark mode'
}
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
.dark-mode {
filter: invert(1) hue-rotate(180deg);
}
.invert {
filter: invert(1) hue-rotate(180deg);
}
'
<button class="btn">
<img src='moon.png' alt="" />
<span>Dark mode</span>
</button>
I am working on Form (Frontend challenge) and stuck with input text field animation.
I have tried to use a placeholder instead of the label but It did not work. I am not sure am I on the right track or not. Sharing the code below. I have to complete it just with Vanilla JS.
When I focus on the input field label goes up as I wanted and the focus out comes back.
But if I fill the input with text, label, and text coming together in the input field. If Input has a text label needs to stay at the top. Thank you in advance.
// console.log("Hey, It's working");
const form = () => {
const inputText = document.querySelector("input[type=text]");
const nameText = document.getElementById("yourname");
inputText.addEventListener("focusin", (e) => {
nameText.classList.add("active");
});
inputText.addEventListener("focusout", (e) => {
nameText.classList.remove("active");
});
};
form();
fieldset {
border: medium none !important;
margin: 0 0 10px;
min-width: 100%;
padding: 0;
width: 100%;
}
#sign-up-form {
padding: 25px;
margin: 50px 0;
}
input[type="text"] {
width: 100%;
border: 1px solid #ccc;
margin: 0 0 5px;
padding: 10px;
border-radius: 4px;
}
label {
font-size: 0.9em;
opacity: 0.5;
-webkit-transition: top 0.2s ease-in-out, font-size 0.2s ease-in-out;
transition: top 0.2s ease-in-out, font-size 0.2s ease-in-out;
}
#sign-up-form {
text-align: center;
}
input {
margin: auto;
}
fieldset {
position: relative;
}
label {
position: absolute;
top: 0;
margin-left: -200px;
margin-top: 10px;
padding: 0 10px;
}
input {
display: block;
}
.active {
top: -20px;
opacity: 1;
background-color: $input-background;
z-index: 1000;
}
<form id="sign-up-form">
<fieldset>
<label id="yourname" for="yourName">Your Name</label>
<input
class="form-control"
type="text"
size="30"
autocomplete="off"
tabindex="0"
required
/>
</fieldset>
</form>
Before removing active class from nameText, you need to check whether the input is empty or not. If the input is empty, there is no need to remove active class from nameText. See below code snippet.
inputText.addEventListener("focusout", (e) => {
if(inputText.value.length == 0)
nameText.classList.remove("active");
});
Additionally, String.prototype.trim should also be used to check for whitespaces in inputText.
I have a checkbox that when i click on it,it changes in color as follows:
.checkmark {
display: inline-block;
width: 22px;
/*height: 22px;*/
height:17px;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
margin-left:50%;
margin-bottom:1px;
}
.checkmark:before {
content: '';
position: absolute;
width: 3px;
height: 9px;
background-color: #ccc;
left: 11px;
top: 6px;
}
.checkmark {
cursor: pointer;
}
.checkmark:after {
content: '';
position: absolute;
width: 3px;
height: 3px;
background-color: #ccc;
left: 8px;
top: 12px;
}
input[type="checkbox"]:checked + .checkmark:before,
input[type="checkbox"]:checked + .checkmark:after {
background: linear-gradient(rgb(42, 104, 149) 0px, rgb(44, 109, 157) 100%);
}
<label style="display: inline;color: #545454;font-weight:100;" dataid="' +this.ID +'" data-nodeid = "' +this.NodeId +'"><input type= "checkbox" style= "display:none;" id="cb' + this.ID + '">MILK
<span for="cb' + this.ID +'" class="checkmark"></span >
</label >
The above works correctly.However when the page gets responsive,when i go from desktop to tablet view or mobile view the tick is no longer highlighted.For example if i click it on tablet view it will get highlighted and then when i make the screen smaller to the mobile site the tick loses its highlight.But if i click it again then the highlight will remain.How can i accomplish having the highlight remain in different responsiveness.
I tried the follwing
function check() {
$("input:checkbox").on('change',function () {
// var $checkmark = $(this);
$('input[id="' + this.id + '"]:checkbox').not(this).prop('checked', this.checked);
});
}
the above passes multiple IDs instead of just one ID at a time.Is there anyway i can assign the highlight in a different way?
I tried to updating aria-checked attribute of a toggle button using JS. It works perfectly fine on Firefox but can't toggle on Chrome.
When I log in JS, apparently the attribute got updated. But not on the actual UI when I viewed with Chrome devtool.
Here's live on codepen.
Please checkout codepen link.
e.target is selecting the span in Chrome, instead of the button on which the event was binded, due to event propagation.
Use e.currentTarget instead of e.target, it will select the button on which the event was originally bound and not any of its child elements.
// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
/* reset button */
button {
background: none;
border: 0;
color: inherit;
padding: 0;
}
/* The switch - the box around the slider */
.switch {
position: relative;
/* display: inline-block; */
width: 60px;
height: 34px;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
/* TODO: put disable color here */
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:focus+.slider {
box-shadow: 0 0 1px #2196f3;
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
/* changing the background while toggling */
[role="switch"][aria-checked="true"] .slider {
background-color: #2196f3;
}
/* toggling the handle */
[role="switch"][aria-checked="true"] .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
<!-- Rectangular switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-rect">
<span class="slider"></span>
</button>
<!-- Rounded switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-round">
<span class="slider round"></span>
</button>