Fill a calculator screen with the inner content of a div element

Currently, I am working on a project where I am using JavaScript to update a calculator's display (.display) based on the numbered button that is clicked.

To achieve this, I am trying to utilize forEach to add a click event listener to each button. This listener will trigger an updateDisplay function which will then update the displayValue variable with the number contained within the div.

Despite my efforts, the code is not functioning as expected and no console errors are being reported. Can anyone offer assistance?

The condensed HTML structure is as follows:

<div class="container">
    <div class="sub-container">
        <div class="display">
            <p id="result-display">
            </p>
        </div>
    <div class="button-grid">
        <div class="item" id="7">
            <p>
            7
            </p>
        </div>

My JavaScript code can be summarized as follows:

//Define variables for display value and display area, initializing the display.
let displayValue = 0;
let displayArea = document.getElementById('result-display');
displayArea.innerHTML += displayValue;

//Update display based on button clicks
const buttons = document.querySelectorAll('.item');
buttons.forEach(button => {
addEventListener('click', () => {
updateDisplay();
})
});

//Function to update displayValue variable  
let updateDisplay = () => {
displayValue = button.innerHTML;
}

Answer №1

One issue you're facing is scoping. Within the loop, you iterate through multiple buttons labeled as button. It may be better to refer to them collectively in the plural form. You then correctly attach an event listener to each one.

I made a slight modification to your code for accessibility reasons. Adding event listeners directly to p may confuse screen readers. By changing the tag to button, many accessibility issues are automatically resolved.

When the event is triggered, we need to determine which specific element was clicked. You could create individual event listener functions for each button, or implement a generic event listener that identifies the clicked button.

Instead of altering the innerHTML of the button itself (which already displays 7), focus on updating the display area with the new value of displayValue. A function like this would be beneficial:


const rerenderCalculatorDisplay = (newValue) => {
  displayArea.innerHTML = newValue;
}

If you want to append to the existing displayValue using +=, you should first retrieve the innerHTML before concatenating. This accounts for scenarios where users input numbers separately such as adding '4 + 4' versus '44'.

A revised version of rerenderCalculatorDisplay might look like this:


const rerenderCalculatorDisplay = (addToDisplay) => {
  if (!isNaN(addToDisplay))
    displayArea.innerHTML = `${displayValue}${addToDisplay}`;
}

Rather than extracting the id from e.target as I did, you could alternatively extract the e.target.innerText.

Alternatively, you could create separate event listeners for each button pressed by the user.

Consider replacing:


const button = document.querySelectorAll('.item');
button.forEach(item => {
  addEventListener('click', () => {
    updateDisplay();
  })

With:


const button = document.querySelectorAll('.item');
button.forEach(item => {
  addEventListener('click', () => {
    updateDisplay(item.id); // specifies which button to update
  })

  const updateDisplay = (valueClicked) => {
    displayValue += valueClicked;
    displayArea.innerText = displayValue; // ensure update is visible to the user
  }

(Container HTML appears here).

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

Tips for creating dynamic images in a flexible design

When creating a fluid layout, you can use em or % for font and div width and height to achieve fluidity. However, the challenge lies in making images resizable. I aim to design a single layout that works seamlessly across all screen sizes and devices. ...

Ways to accomplish a task prior to form submission without relying on preventDefault

How can I perform an action before form submission without using e.preventDefault();? I am faced with a situation where I have two form buttons and need to set a hidden field value before submitting the form. In my Symfony2 framework, when I submit the fo ...

Attempting to utilize React Router V5 to display various layout designs

I have a React application with two different layouts: the "main layout" and the "auth layout". I have noticed that while the main layout pages function correctly, the auth layout pages do not seem to load. When attempting to access "/login", I am directed ...

retrieve HTML content from XML document using the correct user input

I am looking to create a section of an HTML page that can only be accessed through a specific code. The page is coded using pure HTML, CSS, and JavaScript. Here is the proposed logic: User inputs a string into a form Upon clicking the submit button, an ...

Having trouble implementing a cookie on the second domain using the first domain. Can't seem to get it to work properly

Currently, I am working on integrating ajax functionality with PHP. My main objective is to generate a cookie on the page where ajax call is made. The scenario involves two distinct domains - domain1.com and domain2.com. Essentially, the ajax code is imple ...

The function nivoSlider cannot be found in the selected element

I'm having trouble integrating Nivoslider into my website, it's not working for me. Can someone please help me with this issue? Interestingly, it's working fine on my local machine but not on my server. I have tried other suggested solutions ...

The scrolling top value is dynamic when in developer mode

Looking to create a custom scrollbar for my web application. The approach I'm taking involves shifting the default scrollbar 100px to the right and hiding it with overflow:hidden in the parent container</p> $(".scrollbar-vertical").parent(). ...

Dynamic Image Toggle Feature with Laravel and Javascript

Currently, I'm working on developing an eCommerce Shopping Site using Laravel 5.0 for my final year project. Although there is still a long way to go, I have made progress by creating a product show page. Here is a snippet of my controller: pub ...

What is the best way to create a sliding menu that appears from the right side on a mobile device using HTML, CSS, and JQuery

Is there a way to have the menu slide in smoothly from the right side after clicking on the menu bar icon, including sliding the menu bar icon itself? The current code displays the menu directly upon clicking on the menu bar, but I would like it to slide i ...

Stack one image on top of another while maintaining their original proportions using HTML and CSS

I have two images, one is used as a background (A) and the other (B) is positioned over a portion of the background. The issue I am facing is that when the resolution changes, the image B moves and is no longer in the desired position. https://i.sstatic.ne ...

Effective ways to position images within a card alongside a changing title

I have a requirement for displaying multiple cards with dynamic titles fetched from the backend. The challenge is to align images in a row regardless of the title length, ensuring alignment based on the longest title. Below is an illustration of what I am ...

The execution of the 'yarn start-https' command encountered an error and exited with code 1

Struggling to set up the environment for a downloaded project. After running yarn install, yarn build, and yarn start-https, I encountered this error message: Error: error:0909006C:PEM routines:get_name:no start line at node:internal/tls/secure-context ...

How can JavaScript be used to create text in a textbox?

I've encountered an issue with this code snippet I wrote. It's intended to gather a person's name and based on their selection, generate a website URL with their name included at the end. Can you help me figure out why it's not working ...

What is the process for embedding images and text within a nested division element?

I have a website layout with 4 main sections: header, left side, right side, and footer. I would like to further divide the header into two sections - left header and right header. The right header should contain an image along with other options like home ...

Checking for valid usernames using Regex in JavaScript

I have attempted to use the following regex to validate against the criteria listed below, but it seems to fail in certain cases. Can you help me identify what might be wrong with my approach? Regular Expression: /[a-z]|\d|\_{4, 16}$/.test(user ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

Issues arise when trying to integrate iframes with Ionic and AngularJS, as they

Using iframes in my ionic app to display webpages within the application has presented a challenge. This is what I currently have implemented: <iframe class= 'webPage' name= "eventsPage" ng-src="{{object.url}}"></iframe> The issue ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Error: The URL type "workspace:" is not supported: workspace:*

I am embarking on a new project using Gatsby. You can create your project by running the following command: gatsby new YourProjectName2 https://github.com/Vagr9K/gatsby-advanced-starter However, I encountered an error message: info Creating new site fro ...