Azazel
Azazel

Reputation: 593

Changing button text onclick in javascript

I would like to enable a dark mode feature on my website by using a toggle button. I already got dark mode to work now I would like to have the button say Turn on dark mode when it is off and then Turn off dark mode when it is on.

function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
}
body {
	margin: 0;
	font-family: Arial, Helvetica, sans-serif;
	background-color: white;
	color: black;
}

.dark-mode {
	background-color: black;
	color: white;
}
<button onclick="myFunction()">Turn on dark mode</button>

Upvotes: 0

Views: 214

Answers (2)

Ori Drori
Ori Drori

Reputation: 192006

You can use the global .dark-mode class on the body, to change the text on the button. Use a pseudo-element (::before), and set it according the existence of .dark-mode on the body:

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  background-color: white;
  color: black;
}

.dark-mode {
  background-color: black;
  color: white;
}

body.dark-mode .mode-button::before {
  content: 'Turn off dark mode';
}

body:not(.dark-mode) .mode-button::before {
  content: 'Turn on dark mode';
}
<button class="mode-button" onclick="myFunction()"></button>

Upvotes: 2

Bendar
Bendar

Reputation: 119

function myFunction() {
   var element = document.body;
   var btn = document.getElementById("modeSwitcher");
   element.classList.toggle("dark-mode");
   if(element.classList.contains("dark-mode"))
    btn.innerHTML= "Turn off dark mode";
   else 
    btn.innerHTML= "Turn on dark mode";
}
body {
	margin: 0;
	font-family: Arial, Helvetica, sans-serif;
	background-color: white;
	color: black;
}

.dark-mode {
	background-color: black;
	color: white;
}
<button onclick="myFunction()" id="modeSwitcher">Turn on dark mode</button>

Upvotes: 2

Related Questions