Adjust font size using jQuery

Hey there! I have a small question. I want to resize all HTML elements using jQuery, but the current code allows me to increase and decrease the size infinitely.


    var originalSize = $('html').css('font-size');
    
    // Reset
     $(".resetMe").click(function(){
      $('html').css('font-size', originalSize); 
     });

     // Increase Font Size
     $(".increase").click(function(){
      var currentSize = $('html').css('font-size');
      var increasedSize = parseFloat(currentSize) * 1.05;
      $('html').css('font-size', increasedSize);
      
      return false;
     });

     // Decrease Font Size
     $(".decrease").click(function(){
      var currentFontSize = $('html').css('font-size');
      var decreasedSize = parseFloat(currentFontSize) * 0.8;
      $('html').css('font-size', decreasedSize);
      
      return false;
     });
  

I'm looking for a way to limit how many times the font size can be increased or decreased. Any ideas on how to edit this code?

Answer №1

Your code contains a couple of errors, such as when you reassign the resizeCounter value within your click event due to using 'var' in front of it or having an incorrect if statement. Remember that '=' assigns a new value to a variable and is not an equality operator like '==' and '==='. Also, changing the font size on the root element will only affect child elements if you use rem or em as your font size units.

It's important to note that if you increase the font size and then decrease it, the counter will retain its previous value upon the next increase (it does not automatically reset).

var originalSize = $('html').css('font-size');
var increaseCounter = 0;
var decreaseCounter = 0;

// reset
$(".resetMe").click(function() {
  $('html').css('font-size', originalSize);
  increaseCounter = 0;
  decreaseCounter = 0;
});

// Increase Font Size
$(".increase").click(function() {
  increaseCounter += 1;

  if (increaseCounter <= 3) {
    var currentSize = $('html').css('font-size');
    var biggerSize = parseFloat(currentSize) * 1.05;
    $('html').css('font-size', biggerSize);
  }
});

// Decrease Font Size
$(".decrease").click(function() {
  decreaseCounter += 1;

  if (decreaseCounter <= 3) {
    var currentSize = $('html').css('font-size');
    var decreasedSize = parseFloat(currentSize) * 0.95;
    $('html').css('font-size', decreasedSize);
  }
});
html {
  font-size: 16px;
}

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
  font-size: 1rem;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  outline: 0;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

p {
  font-size: 1.3rem;
}

#banner-message {
  background: #fff;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button class="resetMe">reset</button>
  <button class="increase">make bigger</button>
  <button class="decrease">make smaller</button>
</div>

Answer №2

I tried implementing a similar approach but it's still not functioning correctly

var originalSize = $('html').css('font-size');
var resizeCount = 0;
// reset
$(".resetMe").click(function(){
    $('html').css('font-size', originalSize);

});

// Increase Font Size
$(".increase").click(function(){
    var currentSize = $('html').css('font-size');
    var currentSize = parseFloat(currentSize)*1.05;
    $('html').css('font-size', currentSize);
    return false;
    var resizeCount =+1;
    if (resizeCount = 3) {
        event.preventDefault();
    }
});

// Decrease Font Size
$(".decrease").click(function(){
    var currentFontSize = $('html').css('font-size');
    var currentSize = $('html').css('font-size');
    var currentSize = parseFloat(currentSize)*0.95;
    $('html').css('font-size', currentSize);

    return false;
});

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

Display a loading message before fetching remote data in the Bootstrap modal box

Here is the code I am using to load remote PHP data into a Bootstrap modal box: $(function() { $(window).bind("resize", function() { if ($(this).width() < 400) { $('#tabs-content').removeClass('col-xs-10').ad ...

Alter Text Using Typewriter

Recently, I have been experimenting with code on my glitch website, trying to create typewriter text. Thanks to help from a user on StackOverflow, I was able to achieve this effect successfully. However, I am now facing a new challenge. My goal is to make ...

Prioritize loading the JS function before initiating PHP validation

My current challenge involves calling a JavaScript function from PHP upon form submission. The error message I am encountering indicates that the function is not defined. This issue arises because PHP is loaded before JavaScript, resulting in the function ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Submitting multiple parameters in a Jquery POST request

Being a beginner in HTML, jQuery, and AJAX, I have managed to post one object using the code below. However, now I am looking to post multiple objects when clicking the "submit" button (id=analsis) which will send the content of xyz object ids to 127.0.0.1 ...

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

Steps for displaying a bootstrap modal in alignment with the triggering button's position

Recently diving into the world of bootstrap and AngularJs has been quite the learning experience for me. One challenge I encountered was trying to implement a bootstrap modal dialog box to show additional details within a table column. My goal was to hav ...

Achieving uniform alignment of multiple field labels in Bootstrap and Simple Form

Here is the current layout of my form: https://i.sstatic.net/2vZjl.jpg You may notice that the labels are not properly aligned. I would like them to appear like this: https://i.sstatic.net/gm39D.jpg Below is the code for all the input fields: <%= si ...

How to use Javascript, HTML5, and AngularJS to display and print a PDF document within a

I have a situation where I need to load a Base64 encoded PDF as a String from my server into JavaScript in my client application which is built using AngularJS and HTML5. The structure of my HTML code is as follows: <div id="printablePdfContainer"> ...

How can I retrieve an image from a library and automatically update the image in SharePoint every 30 seconds?

I have a web part and I have written the code below: However, it is only fetching one image. How can I fetch all images from the library and change the image every 30 seconds using JavaScript or jQuery? public class MSDN : System.Web.UI.WebControls.WebPa ...

Issues with CSS filters affecting the layout of webpage elements

Is there a way to keep a div pinned to the bottom of the viewport while applying a filter to the body in CSS? I tried using position: fixed; bottom: 0px, but it seems to mess up the positioning when a filter is added to the body. body { filter: bright ...

An issue occurred while attempting to hover over the text in the SVG map

I have a United States map. This code contains CSS for styling the map with different colors for each state. It also includes an SVG image of the map and text labels for each state name. However, there is an issue with the hover effect on the state name ...

ul/div element not displaying background color

I am attempting to showcase navigation items horizontally within a blue colored ribbon. Despite my efforts, the background-color property is not being applied to the ul element. I even tried enclosing it in a div element with a blue background, but still n ...

Is there a way for me to have a background image behave like an img element with img-fluid class as shown in the

Showing 2 rows The issue lies with the first row, as it is not displaying properly and does not resize responsively like the second row. I have tried everything but nothing seems to work. I am attempting to do this because the text and elements in the ...

Unable to refresh CSS file

Struggling with updating my website stylesheet. Everything seems to be in place - files uploaded correctly, cache cleared, even manually refreshed the CSS file multiple times. The only solution that works is renaming the CSS file and updating the link. A ...

Populate DataTable header labels with data from a JSON array

I have successfully created a JSON array that I am using to populate a DataTable. The keys in this array correspond to the label names that should go in the thead section of my table, while the values should go in the tbody. This is what my JSON array loo ...

How can the background of a div be altered when text is typed into an input field?

I need help with the following code. I want to be able to change the background color of a div with the class "target_bg" from red (default) to green every time someone enters or types text into the input field. <div class="target_bg"></div> & ...

How can I personalize the HTML code of images added to my WordPress articles?

I've been on an extensive search trying to find a solution for this issue. I'm aiming to modify the markup of an uploaded image in WordPress from its current form: <div id="attachment_906" style="width: 590px" class="wp-caption aligncenter"&g ...

Establishing the destination for an onclick event to a designated spot

I have divided my body content into two parts. The left side contains a map and buttons, where clicking on a button displays results from Arad.php in another window. How can I target the second half (split right) of my body? <body> <div cla ...