RE: RE: Darkmode toggle button for user settings

Jamie Sammons, modified 3 Years ago. New Member Posts: 5 Join Date: 4/15/22 Recent Posts

Hey,

I try to add a toggle button to the page to toggle between light and dark mode in the settings of the user page, which should be saved. 

I'm using a fragment and only want to change text colors and background-color for every page on the site. 

The HTML and CSS of the button works fine but the style of the page didn't change because I don't know how to call those specifically in Liferay. 

<div class="mode-toggle">
	 <label class="theme-switch" for="checkbox">
        <input type="checkbox" id="checkbox" />
        <div class="slider round"></div>
  </label>
</div>

I tried this:

const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');

    if (toggleSwitch.checked = true) {
			document.body.bgColor = "#272833";
			document.body.style.color = "#fff";
			
    }
    else {        
				document.body.bgColor = "#fff"; 
			document.body.style.color =  "#272833";
    }    
}
toggleSwitch.addEventListener('change', switchTheme, false);

 

thumbnail
Jamie Sammons, modified 3 Years ago. Liferay Master Posts: 593 Join Date: 8/8/14 Recent Posts

Hi ,

In the condition statement it's supposed to be "==" instead of "=" , maybe that's the issue.

Also you can try below code snippet for the same: 

const toggleSwitch = fragmentElement.querySelector('.theme-switch input[type="checkbox"]');
function updateColor() {
if (document.getElementById("checkbox").checked == true) {
	document.documentElement.style.setProperty('bgColor ', '#272833');
    }
    else {    
	document.documentElement.style.setProperty('bgColor ', '#fff');
    }    
}
 toggleSwitch.addEventListener('change', updateColor);

 

Jamie Sammons, modified 3 Years ago. New Member Posts: 5 Join Date: 4/15/22 Recent Posts

Hey,

I corrected the == issue in my code, but forgot to update here. That wasn't the problem, but it works now.

Thanks for you answer.