ArticleZip > How To Change Fontsize By Javascript

How To Change Fontsize By Javascript

In the world of web development, the ability to dynamically change the font size of text on a website can greatly enhance user experience. Thanks to the power of JavaScript, this task can be accomplished with just a few lines of code. In this article, we'll walk you through the process of changing font size using JavaScript, allowing you to customize the appearance of your website with ease.

To begin, let's start by creating a simple HTML file that will serve as the foundation for our font size changing functionality. Within the `` tag of your HTML file, you can add a paragraph element with an id attribute for easy referencing in our JavaScript code:

Html

<title>Change Font Size</title>


    <p id="text">Example Text</p>
    <button>Increase Font Size</button>
    <button>Reset Font Size</button>

In this example, we have a paragraph element with the id of "text" that contains the text we want to manipulate. We've also included two buttons - one to increase the font size and another to reset it to the default size.

Now, let's move on to the JavaScript functionality. In a separate file called 'script.js', we can write the code to change the font size of the text element:

Javascript

function changeFontSize() {
    var textElement = document.getElementById("text");
    var currentSize = window.getComputedStyle(textElement, null).getPropertyValue('font-size');
    var newSize = parseInt(currentSize) + 2;
    textElement.style.fontSize = newSize + "px";
}

function resetFontSize() {
    var textElement = document.getElementById("text");
    textElement.style.fontSize = "16px"; //reset font size to 16px
}

In the `changeFontSize()` function, we first retrieve the text element by its id and then get the current font size using `window.getComputedStyle()`. We increment the font size by 2 pixels and update the style of the text element accordingly.

The `resetFontSize()` function simply resets the font size back to the default size of 16 pixels.

With these functions in place, clicking the "Increase Font Size" button will increment the font size of the text by 2 pixels each time, providing a simple way to adjust the readability of your content. Clicking the "Reset Font Size" button will return the text to its original size.

In conclusion, JavaScript provides a powerful tool for dynamically adjusting font sizes on your website. By following the steps outlined in this article, you can easily implement font size changing functionality to customize the look and feel of your web pages. Experiment with different font sizes to find the perfect fit for your content and enhance the user experience of your website.