Guide to switching a button using JavaScript

I am trying to create a button that will toggle the font size between 16px and 14px when clicked. The button text should also change from "Increase Font" to "Decrease Font" accordingly.

UPDATE: I managed to get it working, but it only toggles twice and then stops functioning.

HTML

<p id="increase">Lorem Ipsum.</p>

<input onclick="font()" style="background-color:#72cf26"  type="submit" value="Increase Font" id = "fontbutton"/>

JS

function font(){
  var fontsize = document.getElementById('increase');
  var fontbutton = document.getElementById('fontbutton');

  if (fontbutton.value == "Increase Font"){
    fontsize.classList.add("font16");
    document.getElementById('fontbutton').value = "Decrease Font";
  }else if (fontbutton.value == "Decrease Font"){
    fontsize.classList.add("font14");
    document.getElementById('fontbutton').value = "Increase Font";
    }
 }

CSS

.font16{
   font-size:16px;
}
.font14{
   font-size: 14px;
}

Answer №1

In order to update the font size dynamically, make sure to utilize fontbutton.value over fontbutton.getElementById.value. Additionally, remove the previous class with fontsize.classList.remove before adding the new one with fontsize.classList.add:

function modifyFontSize(){
     var fontsize = document.getElementById('increase');
     var fontbutton = document.getElementById('fontbutton');
     if (fontbutton.value == "Increase Font"){
          fontsize.classList.remove("font14");
          fontsize.classList.add("font16");
          fontbutton.value = "Decrease Font";
     }else if (fontbutton.value == "Decrease Font"){
          fontsize.classList.remove("font16");
          fontsize.classList.add("font14");
          fontbutton.value = "Increase Font";
     }
}
.font16{
     font-size:16px;
}
.font14{
     font-size: 14px;
}
<p id="increase" class="font14">Lorem Ipsum.</p>
<input onclick="modifyFontSize()" style="background-color:#72cf26"  type="submit" value="Increase Font" id = "fontbutton"/>
          

Answer №2

To meet the mentioned requirement, you can utilize

element.classlist.add and element.classlist.remove functions.

Below is the functional code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            .font16{
                font-size:16px;
                background-color:#72cf26;
            }
            .font14{
                font-size: 14px;
                background-color:#72cf26;
            }
        </style>
    </head>
    <body>
        <p id="increase">Lorem Ipsum.</p>
        <button id="fontbutton" class="font14" onclick="toggleFont()">
            Increase Font
        </button>
        <script>
            function toggleFont() {
                var element = document.getElementById("fontbutton")
                var buttonText = element.innerHTML
                element.classList.remove("font14")
                element.classList.remove("font16")
                if(buttonText.indexOf("Increase") >= 0) {
                    element.classList.add("font16")
                    element.innerHTML = "Decrease font"
                } else {
                    element.classList.add("font14")
                    element.innerHTML = "Increase font"
                }
            }
        </script>
    </body>
</html>

Desired Output:

https://i.sstatic.net/cJy4o.png

For more details:

https://www.w3schools.com/howto/howto_js_toggle_class.asp

Answer №3

$(document).ready(function(){
var flag = true;
$('.btn').click(function(){
    $(this).find('span').toggleClass('hidden');
    if(flag) {
    $('#increase').addClass('font16');
    $('#increase').removeClass('font14');
    flag = !flag;
    }else {
    $('#increase').removeClass('font16');
    $('#increase').addClass('font14');
    flag = !flag;
    }
    });
});
.font16{
   font-size:16px;
}
.font14{
   font-size: 14px;
}
.hidden {
    display: none;
    }

p{ font-size: 10px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="increase">Lorem Ipsum.</p>
    <button class="btn">
    <span>Increse Font</span>
    <span class="hidden">Decrese Font</span>
    </button>

Answer №4

Your method seems overly complicated; instead, JavaScript provides a convenient toggle function for adding or removing classes, returning a boolean value in the process.
The only challenge lies in remembering to include !important to ensure proper sizing.

const paragraphInc = document.getElementById('increase')
  ,   buttonSize   = document.getElementById('fontbutton')
  ;
buttonSize.onclick = () =>
  {
  buttonSize.textContent = (paragraphInc.classList.toggle('Size16'))
                          ? 'Decrease Font'
                          : 'Increase Font'
  }
#fontbutton {
  background-color:#72cf26;
  padding: 7px 12px;
  }
#increase {
  font-size: 14px;
  }
.Size16 {
  font-size: 16px !important;
  }
<p id="increase">Lorem Ipsum.</p>

<button id="fontbutton">Increase Font</button>

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

Combine and emphasize several gridview rows into a single highlighted unit

Imagine you have a gridview that looks like this: FAMILY GROUP COLOR =============================================== | | Poodle | Blue ROW1 | DOG | German Shepherd | Red | | Pitbul ...

Running Selenium tests are not able to initiate Javascript ajax requests

I'm currently troubleshooting a scenario using Selenium that involves the following steps: - When a user inputs text into a textarea, an ajax request is sent, which then adds the text to the database (implemented using django and processed in view.py) ...

The process of extracting a value from an array of objects encountered an error due to the undefined object

I am looking to extract the value from an array within an object while also implementing error checking. The code I currently have checks if a specific key exists in the object and if the value associated with that key is of type array. If both condition ...

Error: Unable to access the 'location' property because it is undefined

Having trouble uploading a product along with an image using AWS S3 (Multer and MulterS3). Every time I try it in Postman, I get the error message "TypeError: Cannot read property 'location' of undefined" specifically pointing to the line where t ...

Automatically install modules during the execution of the Node Webkit build process

After developing a Node Webkit application, I used NW-Builder to generate the run files. The app's size ended up being quite large at 200MB due to the numerous modules utilized. My question is whether it is feasible to create an installer that will f ...

I attempted to set up a Discord bot using JavaScript on Replit, but unfortunately, it seems to only respond when I mention the bot specifically, rather than to any regular

I've successfully created a python discord bot, but I'm encountering issues with the javascript one. Despite trying various solutions from StackOverflow, I'm unable to understand how to get it working. The plethora of online solutions for d ...

Creating dynamic routes in react-router-dom using conditions

I'm currently developing an application using react-router-dom for navigation. I've encapsulated all my <Routes> inside a container provided by Material UI. However, I want my home page to be outside of this container so that I can display ...

How can I enable two-finger scrolling on mobile web browsers?

I am currently tackling a project that involves dragging operations on a canvas, making scrolling with a single finger impractical. My goal is to enable scrolling using two fingers instead. After testing different touch-action values, I discovered that pi ...

What is the best way to assign a value to process.env within an npm script?

After creating a new Vue app (using Vite) with npm init vue@latest and selecting Playwright for e2e tests, the configuration file was generated with a field for setting headless mode: const config: PlaywrightTestConfig = { // ... use: { // ... ...

Beware: Inaccessible code detected in Reactjs usage

Currently, I am working on a ReactJS project where I have integrated two components - PrescriptionIndex and PrescriptionNew. Let's start with the 'PrescriptionNew' component: import React, { Component } from 'react'; import Flo ...

Switch up the webpage's font using a dropdown selection box

I'm interested in adding a drop-down box to my webpage that allows users to change the font of the site when they click on it. I attempted the code below, but it didn't seem to work. Any suggestions? Regards, Sam CSS .font1 p { font-family: " ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

Obtaining HTML data with ajax within a WordPress post

Greetings! I've been putting together a website and I'm eager to include a unique timeline in each of my posts. I'm utilizing WordPress for this project. However, since the timeline I want to insert will vary from post to post, I am unable t ...

Can this layout be achieved using DIV elements?

Struggling to create a unique HTML/CSS layout that extends beyond the center? Imagine a standard horizontally centered page, but with one div expanding all the way to the right edge of the browser window. This design should seamlessly adjust to window res ...

Can you show me the procedure for retrieving a particular element with selenium? (Page Source provided)

Disclaimer: I must admit that my knowledge of HTML and CSS is minimal, so please bear with me! Hello everyone, I am attempting to utilize selenium[Java] to browse a website and retrieve a file. While I managed to successfully get past the login page, I fi ...

Unselecting a span in AngularJS: Switching selection to another span

Whenever I click on an item from my list displayed using ngrepeat, it generates another list specific to the selected element. My goal is to change the background color of the clicked element to indicate it has been selected. However, the problem arises wh ...

Express displaying undefined when referring to EJS variable

After receiving valuable assistance from user Jobsamuel, I have been encountering challenges in displaying the data retrieved from an API call on a webpage: // EJS template to show API data. app.get('/activities', function (req, res) { if (re ...