What's the best way to initiate a script in HTML to alter font size when a button is clicked?

Can someone help me with creating a script that changes the font size when a button is clicked? The buttons should be labeled 'normal', 'medium', and 'large'.

Answer №1

There are multiple ways to adjust the characteristics of HTML elements:

  1. Using the onclick attribute in HTML:

    <button onclick="func()">Text</button>


  1. By utilizing id or class attributes within the HTML code:

    <button id="btnId">Text</button>

    <button class="btnClass">Text</button>

    along with the corresponding JavaScript code -

    For id element:

    let btn_with_id = document.getElementById("btnId") // Accessing element by specific id
    
    btn_with_id.onclick = () => {
        btn_with_id.style.fontSize = "55px" // Can be any unit: em, % etc.
    }
    

    And for multiple elements with the same class (for changing several items):

    let btns_with_className = document.getElementsByClassName("btnClass") // Getting all elements with this class
    for (let btn of btns_with_className) {
        btn.onclick = () => btn.style.fontSize = "55px"
    }
    

    We can also append a className with predefined properties

    btn_with_id.classList.add("btnCustomClass")

    Additionally, there is another way to handle the onclick event - using addEventListener()

    Here's an example:

    btn_with_id.addEventListener('click', event => {
        btn_with_id.classList.add("Your_class")
    })
    

If you wish to modify the button text based on the font-size, here is a solution:

if (btn_with_id.style.fontSize == "55px") btn_with_id.innerHTML = "Large" // You can change both `fontSize` and `innerHTML` here

Answer №2

Changing font size with buttons:

<button type="button" onclick="document.body.style.fontSize = '12px';">Smaller</button>

<button type="button" onclick="document.body.style.fontSize = '16px';">Standard</button>

<button type="button" onclick="document.body.style.fontSize = '20px';">Larger</button>

This code adjusts the font size of the body element only, without affecting other elements unless they are using em or rem units for their font sizes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jeditable failing to process identifier

I've encountered a challenge with updating my database following text modifications, resulting in the error: Unknown column '' in 'field list'. The content of element id is functioning correctly, but the element id itself isn&apos ...

unnecessary shading effect on SVG text

My SVG text suddenly has a strange drop shadow that I can't seem to get rid of. Despite checking the reference guide I purchased on Amazon, I still haven't found any solutions. There are no filters applied and the markup seems to align with examp ...

Angular application functions properly on Firefox and Internet Explorer, but encounters issues on Chrome

I have successfully deployed my angular application on Amazon Web Services S3. It seems to work perfectly fine in Firefox and Internet Explorer, but I am facing some issues with Chrome. Whenever I check the console, I keep getting the following error messa ...

What is causing the issue of buttons within certain div tags not functioning properly when sharing the same classes?

There seems to be an issue with buttons not functioning properly when they are placed inside specific HTML tags. They become unclickable, even in cases where: a. the classes assigned to them are identical to those of working buttons, and b. the enclosing ...

I am having trouble getting my tag to function properly within the if statement of my template

My goal is to show a notification badge in my inbox only if there are more than 0 messages. However, I'm facing an issue with my if statement. I'm uncertain whether it's a syntax problem or a logic error. The message count is correctly displ ...

Create a Vue.js dropdown menu that dynamically changes options based on the capacity of different trips

Imagine a scenario where a user has planned a trip with a specific capacity to accommodate a certain number of individuals. For instance, the trip may be designed for 1 person or up to 6 people. To streamline the process of calculating the total trip price ...

What is the best way to retrieve the text from a linked button within my rad grid using jQuery?

I am facing an issue with a grid that contains link-buttons in the code column. The user can check multiple checkboxes, and when they click on the top button of my page, all selected codes will be displayed in a text box on another page using a jQuery func ...

Utilizing the variable $this outside of an object context within an Ajax function

Encountering the following error: Fatal error: Uncaught Error: Using $this when not in object context in E:\xampp\htdocs\StudentGuideBook\Version1.0\models\AjaxChecking.php:4 Stack trace: #0 {main} thrown in E:\xampp&b ...

Tips for configuring a file using javascript and angular.js

I am in need of some assistance. I would like to create a configuration file that stores all the paths for JavaScript files, which can then be dynamically called and included in the index page using Angular.js or JavaScript. The structure of my files is ex ...

Is there a quick way to apply the !important rule to all properties in a CSS file?

Seeking a quick one-line shortcut to add !important to every CSS property in my extensive CSS file. Any suggestions on making the whole .css file !important? ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

Could JSON be improved for better space efficiency, or is this the standard format?

Within my code, I am using var team = <?php echo json_encode(get_results("SELECT id,name,title,bio,sord,picfn FROM mems ORDER BY sord")); ?>; This code generates a JavaScript array of objects like: var team = [{"id":"1","name":"somename1","title": ...

I seem to have misplaced the plot here, but can someone explain why this tiny snippet of JavaScript isn't functioning properly?

I am looking to create a universal error handler for all my forms var errorHandler = function() { var $errorBox = $('#form-error'); return { add: function(errors) { if ($errorBox.length === 0) { $erro ...

Why does my timer consistently increase by a specific amount every time I refresh?

I've encountered an issue with my Vue.js script that adds time to my stopwatch every time I refresh the page, consistently adding an extra 6 hours. The script consists of a button that starts tracking time when clicked and posts the time to a Django m ...

Having trouble applying CSS styles to the root element despite using a CSS file

My reactjs entry component setup looks like this: import React from "react" import ReactDOM from 'react-dom'; import App from "./js/components/App.js" import './index.css'; ReactDOM.render(<App />, document.getElementById(' ...

Utilize npm to incorporate external JavaScript libraries into Meteor 1.3

Trying to integrate the OpenSeadragon library into my Meteor app has been a bit challenging. After successfully installing it via npm using meteor npm install openseadragon, I found that the OpenSeadragon docs only offer an example using the script tag. T ...

jquery: selecting a specific child div element

Is it possible to target a child div of the current element in jQuery, apply toggle functionality to it, and simultaneously remove the link click effect? Below is the HTML code: <a href="#" class="title">Link</a> <div class="data"> c ...

transition-duration is ineffective in a particular div

Whenever I hover over the purple text, I want it to increase in size using the zoom property. Here is an example: I am facing two issues: The time duration does not seem to work even when I try to apply it within the hover and non-hover classes. Wh ...

The command express is not recognized in the current shell

Encountering a strange error while attempting to install the express-generator with and without using sudo. The necessary commands are: npm install express-generator -g followed by express --ejs name_here. However, upon executing the first command, the fo ...

Unable to trigger click event

I apologize for asking the same question again, but I'm really struggling with this seemingly easy (or difficult?) code problem. Despite trying out Rory McCrossan's solution from here, it still doesn't seem to work for me. Can someone please ...