Ways to decrease font size and insert a line break within a constrained input space?

I am facing an issue where the input box remains static with old numbers when it overflows, and newly typed numbers do not appear at all.

<!DOCTYPE html>
<html>
<body>

 <input type="text" id="output-area" placeholder="0"  oninput="responsiveFont()" style=" width: 225px;
    height: 80px;
    font-size: 40px;
    text-align: right;
    pointer-events: none;">
<br><br>
<button onclick="Addition('1')">1</button>
<button onclick="Addition('2')">2</button>
<button onclick="Addition('3')">3</button>
<br><br>
<button onclick="clearAll()" style="background: red; color: white;">AC</button>
<button class="symbol"  onclick="del()">del</button>

 <script>
 let output_area = document.getElementById('output-area');
 function Addition(newValue){
            output_area.value += newValue;
        }
        
    function clearAll(){
            output_area.value = "";
        }
    function del (){
            output_area.value = output_area.value.slice(0, -1);
        }     

</script> 

</body>
</html>

My goal is to have the input box take a line break and reduce the font size when it overflows, displaying numbers in two lines or maximum three lines. I attempted to achieve this using the following function:

function responsiveFont (){
        output_area.addEventListener('input', () => {
    if (output_area.scrollWidth > output_area.clientWidth) {
    const fontSize = parseInt(window.getComputedStyle(output_area).fontSize);
    output_area.style.fontSize = `${fontSize - 10}px`;
  }
});
}

However, it does not seem to work as intended. If I change the

pointer-events: none;

to

pointer-events: normal;

it only works after manually deleting something from the overflowing input field.

Answer №1

It is recommended to place the responsiveFont function inside the Addition Function, instead of using the oninput event. This is because the oninput event only captures real keyboard input and not button clicks.

let output_area = document.getElementById('output-area');

function Addition(newValue){
  output_area.value += newValue;
  responsiveFont();
}        
function clearAll(){
   output_area.value = "";
   output_area.style.fontSize = '40px';
}
function del(){
  output_area.value = output_area.value.slice(0, -1);
}     

function responsiveFont(){
  console.log(output_area.scrollWidth + " / " + output_area.clientWidth);
  if (output_area.scrollWidth > output_area.clientWidth) {
    const fontSize = parseInt(window.getComputedStyle(output_area).fontSize);
    output_area.style.fontSize = `${fontSize - 10}px`;
  }
}
#output-area{
    width: 225px;
    height: 80px;
    font-size: 40px;
    text-align: right;
    pointer-events: none;
}
<input type="text" id="output-area" placeholder="0">

<br><br>
<button onclick="Addition('1')">1</button>
<button onclick="Addition('2')">2</button>
<button onclick="Addition('3')">3</button>

<br><br>
<button onclick="clearAll()" style="background: red; color: white;">AC</button>
<button class="symbol"  onclick="del()">del</button>

Answer №2

In my experience, using a textarea instead of an input element makes it easier to handle multiple lines of content without the need for manually adding line breaks. To achieve this, I implemented the following solution:

  1. Create a function that reduces the font size when the text area reaches a certain length threshold.

function adjustFontSize() {
        if (output_area.value.length > 8) {
    output_area.style.fontSize = "25px";
  } else {
    output_area.style.fontSize = "40px";
  }
}

  1. Develop another function that disables the textarea with an alert message once it reaches its maximum length:

function disableTextareaOnOverflow(textarea) {
  if (textarea.scrollHeight > textarea.offsetHeight) {
    textarea.disabled = true;
  } else {
    textarea.disabled = false;
  }
  
}

Here is the resulting code snippet:

<!DOCTYPE html>
<html>
<head>
<style>
#output-area{
    width: 200px;
    height: 70px;
    font-size: 40px;
    text-align: right;
    resize: none;
</style>
</head>
<body>

<textarea id="output-area" placeholder="0"></textarea>

<br><br>
<button onclick="Addition('1')">1</button>
<button onclick="Addition('2')">2</button>
<button onclick="Addition('3')">3</button>

<br><br>
<button onclick="clearAll()" style="background: red; color: white;">AC</button>
<button class="symbol"  onclick="del()">del</button>

<script>
let output_area = document.getElementById('output-area');
        output_area.maxLength = 25;

        function clearAll(){
            output_area.value = "";
            output_area.style.fontSize = '40px';
        }
        function del (){
            output_area.value = output_area.value.slice(0, -1);

        }
        function Addition(newValue){
            if (output_area.value.length <= output_area.maxLength) {
                output_area.value += newValue;
              } else {
                 alert("Oops! I can't take anymore. Please try to clear something");
              }
              disableTextareaOnOverflow(output_area);
              adjustFontSize();
        }

        function disableTextareaOnOverflow(textarea) {
          if (textarea.scrollHeight > textarea.offsetHeight) {
            textarea.disabled = true;
          } else {
            textarea.disabled = false;
          }

        }

        function adjustFontSize() {
            if (output_area.value.length > 8) {
            output_area.style.fontSize = "24px";
          } else {
            output_area.style.fontSize = "40px";
          }
        }
</script>

</body>
</html>

To demonstrate the improvement, I have provided links to both the original problem and the solved version. Here is my updated CodePen link. Additionally, you can check out the resolved issue on my GitHub live page: JavaScript Calculator. Thank you for your attention.

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

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Interested in transforming and showcasing dates within a MySQL database?

Here's a form with 10 JQuery UI date pickers set up: $(function() { $("#datepicker").datepicker({ minDate: 'today', maxDate: "+90D", showOn: "button", buttonImage: "images/calendar-new2.jpg", buttonImageOnly: true, dateFormat: "D, dd M, yy" ...

Is there a way to successfully include an apostrophe in a URL?

I am currently utilizing Node.js: var s = 'Who\'s that girl?'; var url = 'http://graph.facebook.com/?text=' + encodeURIComponent(s); request(url, POST, ...) This method is not functioning as expected! Facebook seems to be c ...

Issue with Redux saga not responding to action initiated by clicking on an icon

Declaration of Saga function* DoStuffInSaga({myRef}){ try { console.info("saga running"); return yield delay(1000, 1); } catch(error){ console.warn(error); } } export function* mySaga(){ yield all([ yi ...

Error in External JavaScript File and Uncaught Reference Error

Wanting to utilize a separate Javascript file with my HTML code, I encountered an issue. Here is the code for the HTML document: <!DOCTYPE html> <html> <a href="javascript:showAlert()">Show Alert!</a> <script type="text/jav ...

All web resources need to be included in the web_accessible_resources manifest key

I'm encountering an issue with my Angular app. The error message on the client console reads: Denying load of chrome-extension://fiekimdgbphfmnlbiahcfdgcipcopmep/js/lib/angular/angular.min.js.map. Resources must be listed in the web_accessible_resour ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Guide to customizing the appearance of a Bootstrap Component within an Angular project

Is it possible to completely customize the style/CSS of a component from ng-bootstrap? Here's the issue I'm facing: I have this code... <ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next" style ...

Conceal any errors and warnings from appearing in the console

Many programming languages, such as PHP, provide methods to suppress error and warning messages. Is there a similar approach in JavaScript or jQuery to stop errors and warnings from appearing in the console log? ...

What causes the error "Why am I receiving a "Cannot read property 'length' of undefined" when looping through a pug template?

Currently, I am in the process of developing a project using Node and Express. My objective is to have the home page display signup and login links in the nav bar when the user is not logged in. Initially, everything seemed to be working fine, and I was ab ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

trigger a p:ajax event by employing a right-click action

Currently, I am utilizing JSF and Primefaces 5.2. A peculiar observation I made is that when a commandLink is used with the onclick event and p:ajax, it creates a selection effect. <h:commandLink id="commandLink"> <p:ajax event="click"/> </ ...

Automatically trigger the expansion of all panels within Vuetify using code

I'm attempting to use Vuetify 2.3.5 to programmatically control the opening and closing of expansion panels. <v-expansion-panels accordion> <v-expansion-panel v-for="(item,i) in faqs" :key="i"> <div class ...

adding new data rows to an existing data list using Angular

I am currently working on displaying data from a backend system. The data is coming from a table that receives new rows within a specific time frame. To retrieve these new rows, I have set up a mechanism using an Angular timer. My query pertains to the tem ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

I am having difficulty organizing my text into two grid columns and aligning it in the center

.hero { display: grid; grid-template-columns: repeat(2, 33.45rem); grid-template-rows: 12.5rem; border-bottom: .05em solid #05d31f; width: 69.8rem; height: 16.5rem; } .hero-title { grid-row-start: 1; grid-column-start: 1; } .hero-title h ...

What is the optimal placement for promises in Angular: Factory or Controller?

In my application, I have a basic factory to manage API calls. Currently, the structure looks like this: .factory('apiFactory', function($http){ var url = 'http://192.168.22.8:8001/api/v1/'; return { getReports: function() { ...

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

Exploring a multitude of data within a hefty json log document using node.js

I am dealing with a JSON file named sensorlogs.json that contains data from different sensors transmitting at varying frequencies. The timestamps in the file are not in order and one sensor may have missing entries. The goal is to analyze each sensor&apos ...