Javascript body text size

Change Text Size On Click With JavaScript

A lot of blogs and websites that have a wide range of users tend to have buttons or images that change the text size for easier readability. This can easily be implemented with a bit of JavaScript and some HTML to attach it to. There are libraries out there that do this, but in many cases it is likely overkill. Simplicity is generally better where possible.

The Text-Resizing JavaScript Function

function resizeText(multiplier) < if (document.body.style.fontSize == "") < document.body.style.fontSize = "1.0em"; >document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.2) + "em"; >

Note that line 2 in the code above requires that you specify font-size on the element (it is OK to have a font-size that is specified in pixels). Alright let’s see our options for using the resizeText() function.

The HTML (I use images here but you can use any HTML element)

 Increase text sizeDecrease text size

You can of course unobtrusively add the events like this:

The Unobtrusive Way Using JavaScript

$("plustext").addEvent("click", function() ); $("minustext").addEvent("click", function() );

Here’s a simple example of this all put together. This works flawlessly on at least IE, Firefox, Opera, and Safari (others not fully tested, please give feedback 🙂

Читайте также:  New keyword in php

I’m sure you readers can think of some improvements so let’s see some in the comments!

About Eric Wendelin

Eric Wendelin is a software engineer for Sun Microsystems. When he’s not doing super-secret programming for Sun, he plays indoor soccer, playing Wii with his friends, and cheering on the Colorado Avalanche. He also writes a blog on JavaScript, CSS, Java, and Productivity at eriwen.com

Recent Features

Create a Sheen Logo Effect with CSS

Create a Sheen Logo Effect with CSS

CSS Filters

CSS Filters

Incredible Demos

Create a 3D Panorama Image with A-Frame

Create a 3D Panorama Image with A-Frame

Create a Custom “:selected” Pseudo Selector in MooTools

Create a Custom “:selected” Pseudo Selector in MooTools

Discussion

I’m curious.. what is the point of doing this in JavaScript? Are there major browsers that are incapable of increasing page text size?

I think it’s good to do this in javascript because many users may not know how to change the text size using the browser’s menu. Believe me, you’d be surprised how much I need to explain to customers about their browsers.

@Duuude: This method actually does work for links and stuff, but my site is a bad example because there is hacky stuff in place preventing certain nodes from being resized. I encourage you to cut and paste the code into your Firebug console (replacing “multiplier” with a 1) and convince yourself of this, proving how accessible David’s site is compared to mine. A lesson in JavaScript and a lesson in accessibility. What more could you ask for! 🙂

@Eric: Yep, I went with “em’s” for my theme’s font. How unprogrammer like to use a varying-sized font — we want complete control!

In light of the problem discussed above I have converted over to a more fluid layout. Now everything resizes as expected 🙂

Increase the font size, go to another web site and … back to small text
Increase the font size, follow a link to another web page on same site and … back to small text These ideas seem like they’re worthwhile at first, but they are only any use to your own site. The user never actually learns that they could resize the text for *any* site. I would recommend teaching the user how to use the tool they have in front of them, so instead of it triggering some JavaScript, show then how to do it: http://accessify.com/news/2007/09/teach-a-man-to-fish-or-how-to-resize-text/ Personally, I never bother with on-page tools like this … because I don;t need to 🙂

Ian: I see your point. It may be a good idea to add a cookie to this functionality so that the page remembers the size.

Hi I love it but i need it to be persistent – can you add an example with cookie so that site experience sticks to chosen size please

@Dan: Beat you to that request. Eric is in the process of creating a “part 2” of sorts that saves the font information in a cookie and uses that value on every page. Stay tuned!

This is not a bad idea, I’ve stumbled upon it when got a request to put the JS resizing func on a clients website… too lazy to write my own, and theres no need, so here I am. Though, I do think that this is kind of retarded, there is a tool in a browser… use it! If people dont know how, then they should learn or not, their choice… I recall a quote from bash.org, it went something like this:
“the problem with people is stupidity! I say, take the safety labels off of everything and let the problem work itself out.”

Yeah I agree that most people are stupid but the client wants it (the most stupid people of all) so if anyone figures a way then i’ll help stupid people think less.

I have built a few of these javascript resizers, usually adding something new to each revision. One example of this can be found at http://www.cppht.com which is a housing association site which I built. The problem I found was that I needed a javascript text resizer which allowed for varying text sizes across the site, and kept htem all in proportion to each other when they were resized (i.e. I didnt want everything on the site to be the same font size). To get round this, I simply used a variable which held the current adjustment value (i.e. +2 or -4) which I then used to manipulate each tag as I got to it. The biggest downside to my script (which I havent been able to overcome yet) is that every element on the site must include its own ‘style=”font-size: px;” ‘ tag in order to resize. The settings in my CSS stylesheet dont appear to have an effect when the resize functions looks at the element. Any ideas? If I can solve this problem then I think my script would be complete and very robust! I will of course provide a copy of the script to anyone that wants to take a look.

P.S. Ignore the fact that the example site given spreads horribly across the screen! This is easily solved in sites I have built since.

great script! is there a way to limit the amount of clicks – for example, a user can only increase 2 times, and decrease 1? thanks!

Nice tutorial, I created a similar script that some people might want to take a look at: Change Font Size with JavaScript

Hi Eric, Can you please tell me what’s wrong with this cookies function, it doesn’t work for me. Thanks!

Thank you. I was beginning to despair of ever finding a font-size script that would work in Explorer, Opera, and Firefox, but yours works flawlessly in all three browsers.

First, thankx for this nice little tut.
I´m trying make it work for a css class, insted of a body style, and i can´t get it working.
help please please please

Another approach would be to use JavaScript to load specific style sheets based on what size font has been selected. In this way, you can maintain control over the full layout. You might have 4 different style sheets, each on giving the end user the precise layout that you want them to have. You can also use this method to automatically make your content fit when the user resizes the page in a material way.

Another approach would be to use JavaScript to load specific style sheets based on what size font has been selected. In this way, you can maintain control over the full layout. You might have 4 different style sheets, each on giving the end user the precise layout that you want them to have. You can also use this method to automatically make your content fit when the user resizes the page in a material way.

I found this is the most appropriate method for embedded IE in Windows Mobile, which follows IE5 standards and browser based zoom level came only IE 5.5+.

@Ian Lloyd: Good point but a lot of people prefer to do this with only one click, and changing the font size using the browser tools can make other website look bad so then they have to change it back.. 🙂

how can the JS be modified to target specific tags within the body.
I tried:
document.body.h1.style.fontSize
instead of:
document.body.style.fontSize no luck

Thanks for the great script! However, I am looking for a way to modify the script so that it works, as designed, regardless of the units being used in the CSS definitions? As the script is written, unless ’em’s are used to define the font-size, merging, etc., the properties will not be affected. For example, if I set the following CSS:
p
the font size will change, but not the margin. And if I were to set:
p
nothing would change. Am I missing something simple, or is this functionality more difficult than I am anticipating? Thanks, in advance!

Don’t know what happened to the formatting in my above comment… sorry. It was supposed to have some line breaks in there :-/

This script works okay as long as the user does not discover the browser’s built-in font size options (such as in IE’s View menu. Therefore the script should not only resize the text but also dequately change the selected option in the View menu. Is that possible?

@David Walsh David, it’s not okay (what you stated in your article) to use pixels initially. On the html-page (or in the style sheet) font sizes must be in ’em’ (or percent perhaps, but I never use that). In my previous post ‘dequately change’ should be read as ‘adequately change’of course.

Okay, finally I got it the way I want. It may look a bit different, but without having found the resizer code presented here, I would never been able to write my own variant. So, thank you very much! Originally my default font had the size of 12 pixels (which is approximately 10 points, the standard size used in newspaper printing – I’m a retired journalist, that’s why). Most popular browsers use a 16 pixels letter as their default font. To decrease this to “my” 12, in my stylesheet I downgraded the body font to 75 percent. This downgrades “1em” from 16 to 12 pixels. Furthermore I changed all the pixel values for fonts used inside the body to em, so “12px” became “1em”, “10px” is now “0.835em” et cetera. Note that an a-link not having the href-attribute, does not automatically change the mouse cursor into a pointer! Here is the relevant code in the style sheet:

And this is the code for the html-pages, including a small picture of a pair of spectacles (‘bril’ in Dutch). The titles mean: Default font, Larger font and largest font. And yes, the 3 click-on A’s don’t resize.

Источник

Свойства font-size и line-height

Здесь мы рассмотрим, как соотносятся размеры шрифта и строки, и как их правильно задавать.

font-size и line-height

  • font-size – размер шрифта, в частности, определяющий высоту букв.
  • line-height – высота строки.

Для наглядности посмотрим пример HTML, в котором шрифт и размер строки одинаковы:

Размер шрифта font-size – это абстрактное значение, которое привязано к шрифту, и даётся в типографских целях.

Обычно оно равно расстоянию от самой верхней границы букв до самой нижней, исключая «нижние хвосты» букв, таких как p , g . Как видно из примера выше, при размере строки, равном font-size , строка не будет размером точно «под букву».

В зависимости от шрифта, «хвосты» букв при этом могут вылезать, правые буквы Ё и р в примере выше пересекаются как раз поэтому.

В некоторых особо размашистых шрифтах «хвосты букв» могут быть размером с саму букву, а то и больше. Но это, всё же исключение.

Обычно размер строки делают чуть больше, чем шрифт.

По умолчанию в браузерах используется специальное значение line-height:normal .

Оно означает, что браузер может принимать решение о размере строки самостоятельно. Как правило, оно будет в диапазоне 1.1 — 1.25 , но стандарт не гарантирует этого, он говорит лишь, что оно должно быть «разумным» (дословно – англ. reasonable).

Множитель для line-height

Значение line-height можно указать при помощи px или em , но гораздо лучше – задать его числом.

Значение-число интерпретируется как множитель относительно размера шрифта. Например, значение с множителем line-height: 2 при font-size: 16px будет аналогично line-height: 32px (=16px*2) .

Однако, между множителем и точным значением есть одна существенная разница.

  • Значение, заданное множителем, наследуется и применяется в каждом элементе относительно его размера шрифта. То есть, line-height: 2 означает, что высота строки будет равна удвоенному размеру шрифта, не важно какой шрифт.
  • Значение, заданное в единицах измерения, запоминается и наследуется «как есть». Это означает, что line-height: 32px будет всегда жёстко задавать высоту строки, даже если шрифт во вложенных элементах станет больше или меньше текущего.

Давайте посмотрим, как это выглядит, на примерах:

 
стандартная строка
шрифт в 2 раза больше
шрифт в 2 раза больше

Источник

Оцените статью