ElTee
ElTee

Reputation: 1

How to change background color and font color on click (no jQuery)?

I'm working on an eReader-like project for school and I was instructed to not to use jQuery.

I want to allow users to change the colors of the page based on their preferences. I figured how to change the background-color by using color names in the class of the buttons, but I can't figure how to change the font color (something I really need to do specifically for the black background).

Any help would be appreciated!

HTML:

<div class="textBox">Dummy text</div>
<button class="bisque">sepia</button>
<button class="black">black</button>
<button class="white">white</button>    

JS:

var elems = document.getElementsByTagName('button');

for(var i = 0; i < elems.length; i++) {
     elems[i].onclick = function(e) {
       e.preventDefault();
       var color = this.getAttribute('class');
       document.getElementsByTagName('body')[0].style.background = color;
   }
};

Upvotes: 0

Views: 167

Answers (1)

Terry Wei
Terry Wei

Reputation: 1531

You can change the font color doing the following:

var elems = document.getElementsByTagName('button');
   for(var i = 0; i < elems.length; i++) {
   elems[i].onclick = function(e) {
     e.preventDefault();
     var color = this.getAttribute('class');
     var font_color = this.getAttribute('data-color');
     document.getElementsByClassName('textBox')[0].style.color = font_color;
     document.getElementsByTagName('body')[0].style.background = color;
   }
};
<div class="textBox">Dummy text</div>
<button class="bisque" data-color="black">sepia</button>
<button class="black" data-color="white">black</button>
<button class="white" data-color="bisque">white</button>

Upvotes: 3

Related Questions