Change font, size and color on click in JavaScript
Beginner · 4 min read
Click a button and some text on the page changes how it looks. It is one of the first things people want to do with JavaScript, and it is behind dark-mode switches, "make the text bigger" buttons and error messages that turn red.
In this tutorial you will make a button that changes a paragraph's font, its size and its color when you click it. You need to know a little HTML and what a JavaScript function is. The rest is explained as we go.
The page and the DOM
When a browser loads a page, it turns the HTML into a tree of objects called the DOM (Document Object Model). Each tag becomes an object your JavaScript can read and change. Here is the page for this exercise:
<p id="text">JavaScript Exercises - Emmanuel Akinfulubi</p>
<div><button id="jsstyle">Style</button></div>
The id attribute is a name for one element. document.getElementById('text') finds the element with that name and gives it back to you. If no element has that id, you get null.
The style property
Every element has a style property. Whatever you put there is applied straight to that element, as if you had written a style="..." attribute in the HTML.
There is one rename to learn. CSS names use hyphens, like font-size. In JavaScript a hyphen would mean "minus", so the names are written in camelCase instead: the hyphen goes and the next letter becomes a capital.
font-family -> style.fontFamily
font-size -> style.fontSize
color -> style.color
Here is the exercise. Try it on your own first if you like, or follow along and we will build it together.
1 Change a paragraph’s font, size and colour
easyA page has <p id="text"> and a button. Clicking the button should change the paragraph's font family, font size and colour.
Stuck? Three hints, smallest first
- 1. CSS property names become camelCase in JavaScript:
font-sizeisstyle.fontSize. - 2. Sizes need units.
style.fontSize = 24is silently ignored;‘24px’works. - 3. Setting three properties one by one is fine, but
style.cssTextor a class is usually tidier.
Step 1: find the two elements
Before you can change anything, you need hold of the paragraph and the button.
const p = document.getElementById('text');
const button = document.getElementById('jsstyle');
console.log(p.textContent); // JavaScript Exercises - Emmanuel Akinfulubi
console.log(document.getElementById('nope')); // null
textContent is the text inside an element. Printing it is a quick way to check you found the right one. The null on the last line is what a typo in the id gives you, so if you ever see "Cannot read properties of null", check the id first.
Step 2: write the function that does the styling
Put the three changes in a function, so the button has something to run.
function js_style() {
const target = document.getElementById('text');
target.style.fontFamily = 'Georgia, serif';
target.style.fontSize = '24px';
target.style.color = '#3055d8';
}
Each line sets one CSS property. The values are strings, written exactly as you would write them in a stylesheet.
Look closely at '24px'. It is tempting to write target.style.fontSize = 24, because 24 looks like a number. A browser quietly ignores that: there is no error, and the text just stays the same size. CSS sizes need a unit such as px, rem or %, so always include it.
Step 3: run the function when the button is clicked
addEventListener tells an element "when this happens, run that function". The first argument is the name of the event, here 'click'.
const button = document.getElementById('jsstyle');
const p = document.getElementById('text');
function js_style() {
p.style.fontFamily = 'Georgia, serif';
p.style.fontSize = '24px';
p.style.color = '#3055d8';
}
button.addEventListener('click', js_style);
button.dispatchEvent(new Event('click')); // a click sent from code
console.log(p.style.fontSize); // 24px
Notice that you pass js_style with no brackets. You are handing the function over to be run later, on each click. dispatchEvent(new Event('click')) sends a click from code, which is handy for checking your work without reaching for the mouse.
If you read p.style.color back, a browser may give it to you in its own format, rgb(48, 85, 216), rather than the #3055d8 you wrote. Both mean the same blue.
Clicking a second time is harmless. It sets the same three values again.
The full solution
The panel below builds the page, attaches the listener and fires a click. Its checks confirm all three properties change, the size carries a unit, and the text itself is left alone. Press Run to see the output, and try the live demo above it.
allow-scripts only, so it cannot reach this page.// The page, built without a parser because the stand-in's innerHTML does not
// parse markup. This is the same tree the demo above starts from.
const p = el('p', { id: 'text' }, 'JavaScript Exercises - Emmanuel Akinfulubi');
const button = el('button', { id: 'jsstyle' }, 'Style');
document.body.appendChild(p);
document.body.appendChild(el('div', {}, button));
function js_style() {
const target = document.getElementById('text');
target.style.fontFamily = 'Georgia, serif';
target.style.fontSize = '24px'; // the unit is required
target.style.color = '#3055d8';
}
button.addEventListener('click', js_style);
// A unit-less number is ignored by a real browser. Recorded here to show that
// assigning it does not throw — it just quietly fails to apply.
const before = p.style.fontSize;
console.log('before the click:', JSON.stringify(p.style));
fire(button, 'click');
console.log('after the click :', JSON.stringify(p.style));
console.log('font-size in JS is style.fontSize, not style["font-size"]');
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('nothing is styled to begin with', before, undefined);
test('the font family is set', p.style.fontFamily, 'Georgia, serif');
test('the size is set', p.style.fontSize, '24px');
test('and it carries a unit', /\d(px|rem|em|%)$/.test(p.style.fontSize), true);
test('the colour is set', p.style.color, '#3055d8');
test('the text itself is untouched', p.textContent, 'JavaScript Exercises - Emmanuel Akinfulubi');
test('the element was found by its id', document.getElementById('text') === p, true);
test('an unknown id gives null', document.getElementById('nope'), null);
test('the paragraph is still in the document', p.parentNode === document.body, true);
test('the button is not the paragraph', document.getElementById('jsstyle') === p, false);
test('clicking again is harmless', (() => { fire(button, 'click'); return p.style.fontSize; })(), '24px');
Two things to carry away. CSS property names are hyphenated in a stylesheet and camelCase in JavaScript, so font-size becomes style.fontSize. And every length needs a unit: style.fontSize = 24 throws no error and does nothing at all, which is a slow bug to find. The assertion checks the value ends in a unit for exactly that reason.
Setting styles one property at a time is fine for three properties. Past that, add a class with classList.add() and keep the values in the stylesheet — otherwise your appearance rules end up split between two files.
Common mistakes
- Leaving off the unit.
style.fontSize = 24throws no error and does nothing. Write'24px'. - Calling the function in addEventListener.
addEventListener('click', js_style())runsjs_styleonce, straight away, and passes its result (undefined) as the listener. Passjs_stylewithout brackets. - Running the script before the element exists. If your script sits in the page's
head, the paragraph hasn't been built yet andgetElementByIdreturnsnull. Put the script at the end of thebody, or adddeferto the script tag.
Try it yourself
- Add a second button, "Reset", that puts the paragraph back by setting all three properties to an empty string
''. - Make the button toggle: the first click styles the text, the next click resets it. (Hint: check whether
p.style.fontSizeis empty.) - Move the three values into a CSS class called
fancyand replace the three lines withp.classList.add('fancy').