Skip to content

Instantly share code, notes, and snippets.

@eszterkv
Last active July 22, 2018 04:16
Show Gist options
  • Save eszterkv/3c0f73438e9eee2bce8b7b49988f055f to your computer and use it in GitHub Desktop.
Save eszterkv/3c0f73438e9eee2bce8b7b49988f055f to your computer and use it in GitHub Desktop.
JS snippet for increasing or decreasing font size in a HTML document using jQuery.
function resize(increase_or_decrease) {
const direction = increase_or_decrease;
// First arg is the direction, elements to change follow
for (let i = 1; i < arguments.length; i++) {
let fontsize = parseInt($(arguments[i]).css('font-size'));
if (direction === 'increase') {
fontsize++;
if (fontsize > 20) fontsize = 20; // Prevent text from getting too big
} else if (direction === 'decrease') {
fontsize--;
if (fontsize < 13) fontsize = 13; // Prevent text from getting too small
} else console.log('Resize Error: Direction should be \'increase\' or \'decrease\' (String).');
$(arguments[i]).css('font-size', fontsize);
}
}

Fontsizer.js

JS snippet for increasing or decreasing font size in a HTML document using jQuery.

Usage

In your HTML, create two elements for increasing and decreasing font size, e.g.:
<button id="smaller">Smaller text</button> and <button id="larger">Larger text</button>

Then use jQuery to call the function.

$('#smaller').click(function() {
  resize('decrease', 'p', 'li', '.myclass', '#someId');
});
$('#larger').click(function() {
  resize('increase', 'p');
});

Arguments

All arguments should be strings.

  • First argument is the direction ('increase' or 'decrease'),
  • The following (at least one) arguments are the elements which should change size. They should be elements jQuery can find.
  • To change font size globally, call resize( ... , 'body');.

Requirements

Requires jQuery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment