jack
jack

Reputation: 315

Change font by button onclick or script

I want to make a button that changes an element's font-family by clicking a button.

Here's what I have done;

<h2 id="idname">My title</h2>

<button type="button" 
onclick="document.getElementById('idname').style.font-family = 'Georgia'">
Click Me!</button>

What should I do to complete this script?

Upvotes: 0

Views: 1258

Answers (3)

Ahmad Habib
Ahmad Habib

Reputation: 2384

You have a logical error in your javascript. CSS properties that includes a - in their property name are always targetted as camel case in javascript.

For reference:

CSS notation ------ JavaScript notation

font-family -> fontFamily

font-size -> fontSize

background-color -> backgroundColor

Hence your code will be:

<h2 id="idname">My title</h2>

<button type="button" 
onclick="document.getElementById('idname').style.fontFamily = 'Georgia'">
Click Me!</button>

Upvotes: 2

Luca Corsini
Luca Corsini

Reputation: 736

If you want to change an element's CSS style by using javascript, you must use the camelCase syntax for the rules. change "font-family" with "fontFamily"

<h2 id="idname">My title</h2>

<button type="button" 
onclick="document.getElementById('idname').style.fontFamily = 'Georgia'">
Click Me!</button>

Upvotes: 4

dawalberto
dawalberto

Reputation: 96

Try .style.fontFamily instead of .style.font-family

Upvotes: 4

Related Questions