sahil sanwal
sahil sanwal

Reputation: 93

Changing font size of a JavaScript number variable

I want to change the font size of a number that is assigned to a variable and then printed out.

var secondsPerMinute = 60;
var minsPerHour = 60;

var hoursPerDay = 24;
var daysPerWeek = 7;
var weeksPerYear = 52;
var secondsPerDay =  secondsPerMinute*minsPerHour*hoursPerDay;
document.write(secondsPerDay);
var alpha = "blah";
document.write(alpha.fontsize(10));

Here I want to change the font size of the output secondsPerDay .. for some reason .fontsize() does not work on it. I am new to javascript so apologies if this seems like a foolish question.

Upvotes: 1

Views: 2601

Answers (3)

user663031
user663031

Reputation:

According to the MDN page on String#fontsize:

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Nor should you use document.write, for many reasons.

Write output into HTML elements defined on your page, styled using CSS. For example:

<span id="secondsPerDay" style="font-size: 10px; "></span>
document.getElementById('secondsPerDay').textContent = secondsPerDay;

Upvotes: 3

Nick Zuber
Nick Zuber

Reputation: 5637

EDIT:

The fontsize function is a deprecated method from the String object and you should avoid using it. See some of the other solutions people have posted as a safer alternative.

I recommend outputting HTML and setting the font-size using inline CSS:

document.write('<span style="font-size: 10px">' + secondsPerDay + '</span>');
                             ^^^^^^^^^^^^^^^

Updated fiddle


You have to also apply fontsize() to the secondsPerDay:

document.write(secondsPerDay.toString().fontsize(10));

See your working code here.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

change the last line to

document.write("<span style='font-size:10px;'>"+secondsPerDay+"</span>");
document.write("<span style='font-size:10px;'>"+alpha+"</span>");

use font-size property of the css

after checking @torazaburo's answer, try to use innerHTML rather than document.write

document.body.innerHTML += "<span style='font-size:10px;'>"+secondsPerDay+"</span>";
document.body.innerHTML += "<span style='font-size:10px;'>"+alpha+"</span>";

Upvotes: 1

Related Questions