I read that either local storage or session storage would do the trick, but I'm having a hard time trying to make it work.
function changeStyleByClass(className, classToggle){
var element = document.getElementsByClassName(className);
for (var i=0; i < element.length; i++) {
element[i].classList.toggle(classToggle);
}}
document.getElementById("bulb").addEventListener("click", () => {
changeStyleByClass("bgcolor-lightdark", "dark-mode");
changeStyleByClass("nav", "dark-mode");
changeStyleByClass("nav-item", "dark-mode");
changeStyleByClass("card", "dark-mode");
changeStyleByClass("container", "dark-mode");
changeStyleByClass("bulbicon","dark-mode");});
I'd like to navigate through pages and still keep the theme that is currently on.
Thanks in advance!
You can use localStorage.setItem to store data and localStorage.getItem to retrieve data. One thing that I've noticed is that your light bulb button turns dark mode on, but doesn't turn dark mode off. I have a solution that also simplifies your process of changing themes.
var togButton = document.getElementById("togButton");
//Check localStorage
//It's commented out because it doesn't work in Stack Overflow snippet
//darkOn = localStorage.getItem("dark") == "true" ? true : false;
setTheme();
function setTheme(){
//Save to localStorage
//It's commented out because it doesn't work in Stack Overflow snippet
//localStorage.setItem("dark", darkOn ? "true" : "false");
if(darkOn){
document.body.setAttribute("theme", "dark");
togButton.innerHTML = "Turn off dark mode.";
}
else{
document.body.setAttribute("theme", "light");
togButton.innerHTML = "Turn on dark mode.";
}
}
var darkOn = false;
function toggle(){
darkOn = !darkOn;
setTheme();
}
togButton.addEventListener("click", toggle);
/*By doing body[theme=dark] it only takes effect if the <body> tag has an attribute called theme which is dark.*/
body[theme=light] .sampleClass{
color: black;
background-color: white;
}
body[theme=dark] .sampleClass{
color: mediumseagreen;
background-color: black;
}
<body>
<h1 class="sampleClass">Theme changes.</h1>
<button id="togButton">Turn on dark mode.</button>
</body>
This method is easier because you don't need to manually type all of the classes you want to turn to dark mode, you can just have bot dark and light modes in the CSS file.
I hope you understand the javascript + css. Good luck and ask me if you can't understand part of it.
Edit: Called setTheme() right away.
Edit 2: Explanation
The part which is localStorage.getItem("dark") == "true" ? true : false" is called turnary. The turnary syntax is condition ? value if true : value if false. It is basically the same thing as doing
if(localStorage.getItem("dark") == "true"){
darkOn = true;
}
else{
darkOn = false;
}
This is because localStorage is like a Map where the keys and values are both strings.
Moving on to the next part.
darkOn = false; Just declares the variable darkOn and by default it if false. The toggle function changes darkOn to be the opposite of what it is. the exclamation mark negates boolean values, so darkOn = !darkOn; turns darkOn to false if it was previously true, and true if it was previously false.
Then it calls the setTheme function to update the theme attribute in the <body> tag, causing the css to change. It also saves the current value to localStorage.
Related
I am trying to apply Dark Mode To My Website. I am using the code given below to do so.
!(function () {
var t,
e = document.getElementById("darkSwitch");
if (e) {
(t =
null !== localStorage.getItem("darkSwitch") &&
"dark" === localStorage.getItem("darkSwitch")),
(e.checked = t)
? document.body.setAttribute("data-theme", "dark")
: document.body.removeAttribute("data-theme"),
e.addEventListener("change", function (t) {
e.checked
? (document.body.setAttribute("data-theme", "dark"),
localStorage.setItem("darkSwitch", "dark"))
: (document.body.setAttribute("data-theme", "light"),
localStorage.setItem("darkSwitch", "dark"));
});
}
})();
You can check it out here http://anayaadventure.com/
Everything is working fine but the problem is now suppose I turn the dark mode off and I refresh the page, then the page again loads in dark mode. Why is this happening and how can I solve it.
Thanks for any kind of help in advence.
It looks like you never set localstorage back to "light" in the toggle-event
e.checked
? (document.body.setAttribute("data-theme", "dark"),
localStorage.setItem("darkSwitch", "dark")) //set to dark
: (document.body.setAttribute("data-theme", "light"),
localStorage.setItem("darkSwitch", "dark")); //set item to "light" instead of "dark" ?
And if you edit the local storage value manually to "light" it goes back to lightmode
so i think you want to change the last line to localStorage.setItem("darkSwitch", "light"));
Addition to that i like the layout and design of the site!
Need to know how I could possibly save the state of the darkmode?
I got this js code right here:
$('#switch').on('click', () => {
if ($('#switch').prop('checked')) {
$('body').addClass('dark');
$('main').addClass('darklight');
$('footer').addClass('darklight');
$('.topnav').addClass('darklight');
$('.lightm').addClass('darklight');
$('section').addClass('darklight');
$('button').addClass('button');
$('.links').addClass('llinks');
} else {
$('body').removeClass('dark');
$('body').addClass('light');
$('main').removeClass('darklight');
$('main').addClass('light');
$('footer').removeClass('darklight');
$('footer').addClass('light');
$('.topnav').removeClass('darklight');
$('.topnav').addClass('light');
$('.lightm').removeClass('darklight');
$('.lightm').addClass('light');
$('section').removeClass('darklight');
$('section').addClass('light');
$('button').removeClass('button');
$('button').addClass('dbutton');
$('.links').removeClass('llinks');
$('.links').addClass('dlinks');
}
})
Here is the code in Codepen with the html and css things:
https://codepen.io/TRGYT/pen/eYmNBPo
Does anyone have idea on how to achieve this? And can this darkmode state also be saved for other sites I created?
Please find the site here:
https://15min.netlify.com
Sorry in advance for the bad code, I'm a beginner...
Welcome to the world of coding. Before we get to the problem, it will be of some use to you to get to grips with the DRY principle (Don't Repeat Yourself). Your code (20 or so lines) could easily be abbreviated to just four. For example:
$("#switch").on("click", () => {
$("body").toggleClass("dark"));
// Local storage. Will get to this later
});
You could then change your CSS to respond to whether or not the body tag has the dark class. Much cleaner.
As for saving the state of the dark mode: use window.localStorage like so:
if (window.localStorage) {
const darkMode = window.localStorage.getItem("darkMode");
if (darkMode) {
$("body").addClass("dark");
} else {
$("body").removeClass("dark");
}
}
I found a way that wored. The one answer I got helped me understand it, but I was too lazy to implement it. But still thank you!
function activateDarkMode() {
$('body').addClass('dark').removeClass('light');
$('main').addClass('darklight').removeClass('light');
$('footer').addClass('darklight').removeClass('light');
$('.topnav').addClass('darklight').removeClass('light');
$('.lightm').addClass('darklight').removeClass('light');
$('section').addClass('darklight').removeClass('light');
$('button').addClass('button').removeClass('button');
$('.links').addClass('llinks').removeClass('dlinks');
}
function deactivateDarkMode() {
$('body').removeClass('dark').addClass('light');
$('main').removeClass('darklight').addClass('light');
$('footer').removeClass('darklight').addClass('light');
$('.topnav').removeClass('darklight').addClass('light');
$('.lightm').removeClass('darklight').addClass('light');
$('section').removeClass('darklight').addClass('light');
$('button').removeClass('button').addClass('dbutton');
$('.links').removeClass('llinks').addClass('dlinks');
}
$('#switch').on('click', () => {
if ($('#switch').prop('checked')) {
activateDarkMode();
localStorage.setItem("darkmode", "enabled")
} else {
deactivateDarkMode();
localStorage.setItem("darkmode", "disabled")
}
});
let mode;
mode = localStorage.getItem("darkmode");
if (mode == 'enabled') {
activateDarkMode();
$('#switch').prop('checked', 'checked');
}
All I did was putting the addClass and removeClass into a function. He also added the localStorage and let the localStorage be in a variable called mode. After I created these things, I put them into an if to check if the darkmode is turned on or not.
So I have a table, with which I need to be able to sort and filter (form submit) as well as being able to show and hide columns. I have a simple checkbox that does nothing but toggle the columns. I have been able to get that to work properly, but my problem now is that I need to save the state throughout the entire page lifecycle -- which doesn’t happen.
The basic column show/hide is in the page itself, right after the table:
#section Scripts {
<script type="text/javascript">
$('input[name="columnControl"]').on('switchChange.bootstrapSwitch', function (event, state) {
if (state) {
$("th.status").removeClass("columnHide");
$("td.status").removeClass("columnHide");
$("th.information").addClass("columnHide");
$("td.information").addClass("columnHide");
$("td#p1").attr('colspan', 4);
$("td#p2").attr('colspan', 6);
localStorage.setItem('columnControl', 'true');
} else {
$("th.status").addClass("columnHide");
$("td.status").addClass("columnHide");
$("th.information").removeClass("columnHide");
$("td.information").removeClass("columnHide");
$("td#p1").attr('colspan', 2);
$("td#p2").attr('colspan', 3);
localStorage.setItem('columnControl', 'false');
}
});
</script>
}
So please note: the above DOES WORK, at least in terms of showing and hiding the columns.
Now, the best method I have found so far for saving information through the page cycle is via the localstorage setting, as seen in the code above. This works splendidly for tabs on other pages, but I have been unable to get it to work for my table and bootstrap switch.
Specifically:
On page load, I want the switch to be conditional on the state of the localstorage setting. If it is true or false, the switch needs to be at the appropriate setting, and the appropriate classes need to be set for the columns. If there is no localstorage content (no True or False stored), I need the switch to be ON (true) and certain classes set (a default case).
On form submit (a GET, not a POST), I need to have the switch and all applied classes to remain the same as they were, and to NOT revert to a default case.
If the user leaves the page and returns to it, the switch and classes should remain at their last state and to not revert to the default.
The best I have been able to come up with is this:
#section Scripts {
<script type="text/javascript">
$( document ).ready(function() {
var columnState = localStorage.getItem('columnControl'); //grab the localstorage value, if any
if (columnState) { //does the localstorage value even exist?
$('input[name="columnControl"]').bootstrapSwitch('setState', columnState); //if localstorage exists, set bootstrap switch state based off of localstorage value
if (columnState == 'true') { //if localstorage value == true
$("th.status").removeClass("columnHide");
$("td.status").removeClass("columnHide");
$("th.information").addClass("columnHide");
$("td.information").addClass("columnHide");
$("td#p1").attr('colspan', 4); //set tfoot colspans
$("td#p2").attr('colspan', 6);
} else { //if localstorage value == false
$("th.status").addClass("columnHide");
$("td.status").addClass("columnHide");
$("th.information").removeClass("columnHide");
$("td.information").removeClass("columnHide");
$("td#p1").attr('colspan', 2); //set tfoot colspans
$("td#p2").attr('colspan', 3);
}
} else { //if localstorage value doesn't exist, set default values
$('input[name="columnControl"]').bootstrapSwitch('setState', true);
$("th.information").addClass("columnHide");
$("td.information").addClass("columnHide");
}
});
$('input[name="columnControl"]').on('switchChange.bootstrapSwitch', function (event, state) {
… first script, above …
});
</script>
}
The actual Bootstrap Switch is initialized by a global JS file, via
$("input[type=checkbox]").bootstrapSwitch(); // checkbox toggle
which appears in the head of the webpage.
I have two groups of columns, information and status which comprise 80% of the columns between them. Three columns have no flag for being hidden or unhidden, because they are meant to be displayed at all times.
for test if the local storage exist use :
columnState === null
You just need to fire the switchChange event after define the default value
Full exemple :
#section Scripts {
<script type="text/javascript">
$( document ).ready(function() {
$('input[name="columnControl"]').on('switchChange.bootstrapSwitch', function (event, state) {
if (state) {
$("th.status").removeClass("columnHide");
$("td.status").removeClass("columnHide");
$("th.information").addClass("columnHide");
$("td.information").addClass("columnHide");
$("td#p1").attr('colspan', 4);
$("td#p2").attr('colspan', 6);
localStorage.setItem('columnControl', true);
} else {
$("th.status").addClass("columnHide");
$("td.status").addClass("columnHide");
$("th.information").removeClass("columnHide");
$("td.information").removeClass("columnHide");
$("td#p1").attr('colspan', 2);
$("td#p2").attr('colspan', 3);
localStorage.setItem('columnControl', false);
}
});
var columnState = localStorage.getItem('columnControl'); //grab the localstorage value, if any
if (columnState === null) { //does the localstorage value even exist?
columnState = true //if localstorage value doesn't exist, set default values
}
$('input[name="columnControl"]').bootstrapSwitch('setState', columnState);
</script>
}
I am creating a wizard control pages using the FuelUX wizard plugin
http://getfuelux.com/javascript.html#wizard
And I am trying to disable the NEXT button only on the STEP1 of the wizard.
Kindly check this image for better understanding:
http://i.imgur.com/xlhwu2j.png
I would love to have some help on this. Let me know if need anything from my side.
Ok. After much research I just have this solution for you. You need to modify the plugin fuelux.js. Take unminified version of fuelux.js and find below line of code
var canMovePrev = ( this.currentStep > 1 ); //remember, steps index is 1 based...
var isFirstStep = ( this.currentStep === 1 );
var isLastStep = ( this.currentStep === this.numSteps );
// disable buttons based on current step
if ( !this.options.disablePreviousStep ) {
this.$prevBtn.attr( 'disabled', ( isFirstStep === true || canMovePrev === false ) );
}
// change button text of last step, if specified
var last = this.$nextBtn.attr( 'data-last' );
if(isFirstStep) //Add this line
{
this.$nextBtn.attr( 'disabled', ( isFirstStep === true || canMoveNext === false ) );
}
The above line you can find it in setState: function() { which is in
Line number 3652
Let me know if you face any issue
EDIT: and to work with you alternate next button you can write it as below
$(document).ready(function(){
$('.btnext').on('click',function(){
$('.wizard').wizard('next');
$nextBtn = $('.wizard').find( 'button.btn-next' );
$nextBtn.removeAttr('disabled');
});
});
Add your alternate button wherever you want and just add a class btnext to it.
I really tried all the suggestions given by peoples. I dont know why none seemed to work for me. May be bacause I didn't provide enough information. Out of several methods I tried. I found this one to be the easiest.
protected void NextButton_Click(object sender, WizardNavigationEventArgs e)
{
//Suppose You have a control on your webpage. Just check if it has
//the information you require. In my case lblpasskeytextbox
//and if the condtion is not fulfilled I am not letting user to move
//next page
if (lblPasskeyInformation.Text[0] == 'I')
{
e.Cancel = true;
return;
}
}
After reading the fuel ux documentation, here seems to be a hack that allows you to disable a specific step without modifying any source fuelux.js code.
$wizard.on('actionclicked.fu.wizard', function (evt) {
//Check the current step
var currentStep = $wizard.wizard('selectedItem').step;
//If current step needs to be disabled, disable it and then return.
if (currentStep === 1)
{
evt.preventDefault();
return;
}
});
Please note that $wizard here is just my way of saying $('#myWizard') as described in the fuel ux documentation.
How reset label property.
It means, initially we set the cursor property as #Hand Pointer, then i want to change cursor property value as reset. i should not get hand symbol while doing some other operation. it should be fully disabled.
i tried one way but its not working.
function disableCancelLbl() {
log.info("inside disableCancelLbl");
var lblCancel = createCustomer.getServer().getJSXByName("lbl_ctId_cancel");
lblCancel.setEvent("", jsx3.gui.Interactive.JSXCLICK);
lblCancel.setClassName("buttonTextStyleOff");
lblCancel.setCursor("default",true);
log.info(lblCancel.getCursor());
lblCancel.repaint();
//reset(lblCancel.getCursor());
log.info(lblCancel.getCursor());
}
after repainting, again its changing to hand pointer.
Here's what I use to set/reset the cursor on a button. The setCursor methods seem to work, but the reset to default doesn't work for Chrome :-(
rsh.setWaitCursor = function(button)
{
button.setEnabled(jsx3.gui.Form.STATEDISABLED); button.repaint();
// WaitCursor reset not working in Chrome !!
// 'root' not overwriting wait cursor !
if( !rsh.isChrome ) {
button.setCursor("wait",true);
}
}
rsh.resetWaitCursor = function(button)
{
button.setEnabled(jsx3.gui.Form.STATEENABLED); button.repaint();
// WaitCursor reset not working in Chrome !!
if( !rsh.isChrome ) {
button.setCursor("default",true);
}
}