In this tutorial we will learn how to Change font-size using JavaScript. JavaScript and HTML codes are give below.
Table of Contents
HTML Code
HTML Code is given below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Font Size using JavaScript</title>
</head>
<body>
<p id="text">Change My Font Size</p>
<button onclick="changeSize(1)">+</button>
<button onclick="changeSize(2)">-</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code given below.
<script>
function changeSize(x){
var font = window.getComputedStyle(document.getElementById("text")).fontSize; // getting font size
font = font.replace(/\D/g,''); // removing 'px' from font size
font = Number(font); // converting string to number to perform addition and subtraction
if(x==1){
font = font+1;
document.getElementById('text').style.fontSize = font + 'px';
}
else{
font = font-1;
document.getElementById('text').style.fontSize = font + 'px';
}
}
</script>
Video Tutorial
Watch video tutorial on How To Change font-size using JavaScript.