Creating a calculator with JavaScript event listeners - easy steps to follow!

I'm currently working on a JavaScript calculator project and facing challenges in understanding how to create variables for storing targeted DOM elements, input/output values, and adding event listeners to retrieve data from buttons upon clicking.

I am planning to utilize the function(event) method to display the button value (whether it's a number or operation) on the screen. I also intend to use event.target.dataset.num to extract and store the value as a new variable to be added to the screen display.

Here is a snippet of my current code:

//3.
//Changing colors of operation buttons 

//Setting color for Multiplication
const multiplyColor = document.getElementById('multiply')
multiplyColor.style.backgroundColor = "green"

//Setting color for Division
const divideColor = document.getElementById('divide')
divideColor.style.backgroundColor = "red"

//Setting color for Subtraction
const subtractColor = document.getElementById('subtract')
subtractColor.style.backgroundColor="blue"

//Setting color for Addition
const addColor = document.getElementById('add')
addColor.style.backgroundColor="yellow"

//Changing font color of numbers to blue for better visibility
const num1 = document.getElementById('number1')
num1.style.color="blue"
... (similar lines for numbers 2-9)

//Customizing clear button style
const clearBtn = document.getElementById('clear')
clearBtn.style.color="white"
clearBtn.style.backgroundColor="black"

// Inserting `memoryStoreButton` before the `clear` button:
var memoryStoreBtn = document.createElement("BUTTON");
memoryStoreBtn.innerHTML = "MS";
clear.before(memoryStoreBtn);

//Inserting `memoryClearButton` before `memoryStoreButton`
var memoryClearBtn = document.createElement("BUTTON");
memoryClearBtn.innerHTML = "MC";
memoryStoreBtn.before(memoryClearBtn);

//Inserting `memoryRestoreButton` before `memoryClearButton`
var memoryRestoreBtn= document.createElement("BUTTON");
memoryRestoreBtn.innerHTML = "MR";
memoryClearBtn.before(memoryRestoreBtn);

const btnClick = document.querySelector(".btn8 .btn-grey");
/*
btnClick.addEventListener('click', function(event){
})
*/
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  }
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  }
.calculator8 {
  flex: 0 0 40%;
  }
.screen8 {
  width: 100%;
  font-size: 7rem;
  padding: 0.5rem;
  background: rgb(41,41,56);
  color: white;
  border:none;
  }
.buttons8 {
  display: flex;
  flex-wrap: wrap;
  transition: all 0.5s linear;
  }
button {
  flex:0 0 25%;
  border: 1px solid black;
  padding: 0.25rem 0;
  transition: all 2s ease;
  }
.btn-grey {
  background: rgb(224,224,224);
  }
.btn8 {
  font-size: 4rem;
  }
<section class="calculator8">
  <h1> Calculator 8 </h1>
  <form>
    <input type="text" name="" id="numberBox" class="screen8">
  </form>
  <div class="buttons8"> 
    <!-- operation buttons -->
    <button id="multiply" type="button" class="btn8 btn-mul" data-num="*">*</button>
    <button id="divide" type="button" class="btn8 btn-div" data-num="/">/</button>
    <button id="subtract" type="button" class="btn8 btn-sub" data-num="-">-</button>
    <button id="add" type="button" class="btn8 btn-add" data-num="+">+</button>
    <!-- number buttons -->
    <button id="decimal" type="button" class="btn8 btn-grey" data-num=".">.</button>
    <button id="number9" type="button" class="btn8 btn-grey" data-num="9">9</button>
    <button id="number8" type="button" class="btn8 btn-grey" data-num="8">8</button>
    <button id="number7" type="button" class="btn8 btn-grey" data-num="7">7</button>
    <button id="number6" type="button" class="btn8 btn-grey" data-num="6">6</button>
    <button id="number5" type="button" class="btn8 btn-grey" data-num="5">5</button>
    <button id="number4" type="button" class="btn8 btn-grey" data-num="4">4</button>
    <button id="number3" type="button" class="btn8 btn-grey" data-num="3">3</button>
    <button id="number2" type="button" class="btn8 btn-grey" data-num="2">2</button>
    <button id="number1" type="button" class="btn8 btn-grey" data-num="1">1</button>
    <button id="number0" type="button" class="btn8 btn-grey" data-num="0">0</button>
    <button id="equals" type="button" class="btn8 btn-grey">=</button>
    <button id="clear" type="button" class="btn8 btn-grey">C</button>
  </div>
</section>

Answer №1

I have redesigned your calculator in a more straightforward and intuitive manner, allowing you to handle each button press with a single event handler that identifies the pressed button. This setup provides a solid foundation for coding tasks. Enjoy exploring the possibilities :)

document.querySelector(".buttons8").onclick = function(e) {
if(e.target.nodeName === "BUTTON") {
console.log(`${e.target.textContent} is pressed`);
//perform action
}
}
* {
box-sizing: border-box;
}
.calculator8 {
width: 300px;
}
.buttons8 {
display: flex;
flex-wrap: wrap;
width: 100%;
}
.buttons8 button {
width: 75px;
height: 60px;
font-size: 150%;
}
.screen8 {
width: 100%;
height: 80px;
background-color: #333;
}
.b_blue {
background-color: blue;
}
.b_red {
background-color: red;
}
.b_yellow {
background-color: yellow;
}
.b_green {
background-color: green;
}
.b_lgray {
background-color: #ddd;
}
.b_vlgray {
background-color: #eee;
}
.b_black {
background-color: black;
}
.t_white {
color: white;
}
<section class="calculator8">
<h1>Calculator 8</h1>
<input type="text" class="screen8" disabled>
<div class="buttons8">
<!-- operation buttons -->
<button class="b_green">*</button>
<button class="b_red">/</button>
<button class="b_blue">-</button>
<button class="b_yellow">+</button>
<!-- number buttons -->
<button class="b_lgray">.</button>
<button class="b_lgray">9</button>
<button class="b_lgray">8</button>
<button class="b_lgray">7</button>
<button class="b_lgray">6</button>
<button class="b_lgray">5</button>
<button class="b_lgray">4</button>
<button class="b_lgray">3</button>
<button class="b_lgray">2</button>
<button class="b_lgray">1</button>
<button class="b_lgray">0</button>
<button class="b_lgray">=</button>
<!-- other buttons -->
<button class="b_vlgray">MR</button>
<button class="b_vlgray">MC</button>
<button class="b_vlgray">MS</button>
<button class="b_black t_white">C</button>
</div>
</section>

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

Regular expressions can be used to extract specific attributes and inner content from a div element within a contentEditable container

Context I am currently developing a tagging system called @Name for my website. Successfully, I have managed to detect names upon keystroke and replace the content with the corresponding div class='tag' data-id='User-id'>Name</di ...

The columnFilter plugin in Datatables is failing to initialize

I have a pre-existing table that needs to be customized and initialized properly. <table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table"> <thead> <tr> <th style="width: 10px;" ...

Tips for extracting HTML tags directly from JSON data

In my dataset, I have a JSON illustration [{ "Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n< ...

Issue with dynamic code detected by Sys.Application.add_init

I am facing a challenge with an older application that I recently took over ownership of. My efforts to successfully run it have been partially fruitful, as I am encountering some strange behavior that seems to be related to Internet Explorer 11. Interesti ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

What is the best way to display a poster image in a video element even if the aspect ratio of the poster image does not match the video element?

At this moment, the compatibility of this feature has been tested only in WebKit browsers. When a poster image is applied to a <video> element using the poster attribute, it appears before the user starts playing the video (default behavior). Howeve ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

Activate tooltip when hovering over the <img> element

I am having trouble implementing a tooltip using CSS for an <img> element. While I have successfully added a tooltip to <a href> </a> tags, applying the same functionality to an <img> tag has proven difficult. http://jsfiddle.net/ ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...

Autocomplete with Avatar feature in Material UI TextField

Is it possible to display an avatar in the text field of the autocomplete material-ui component when using the getOptionLabel prop, which only accepts a string? The expected UI shows a profile picture and name for each option. Can we achieve the same thi ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Issue with border in a nested table within an HTML table

I am faced with an issue in styling nested tables. My goal is to have borders on both tables, but I specifically need only the bottom border of the inner table without the top, right, and left borders. The default border style can be achieved using the fol ...

Is the Bootstrap navigation bar collapse button visible on larger screens?

How can I make my Bootstrap navbar collapse button work on big screens the same way it does on mobile devices? <nav class="navbar navbar-expand-md navbar-light bg-light"> <a class="navbar-brand" href="#">Default</a> <button ...

How to incorporate visionmedia debug into an Angular 2 application using System.js, and effective ways to record messages?

Currently I am working on a MEAN stack application with Angular 2 as the frontend. The express backend has successfully utilized debug. However, I am facing issues while trying to import debug cleanly into either app.components.ts or main.module.ts. Any su ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

Is there a way to enlarge all web page elements simultaneously without causing displacement?

Essentially, I am attempting to replicate the functionality that Twitter has on their webpage when you use CTRL+ to zoom in or increase the size of the web page. http://twitter.com/ Currently, I am experiencing displacement of elements upon zoom in and h ...

Discover the power of jQuery: Incorporating unique dynamic inputs within dynamic divs

I have a piece of PHP code that looks like this: foreach ($questions as $q){ foreach ($answers as $a) { echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$ ...

How can I repeatedly substitute a word in the ajax response object?

Let's say we have an AJAX response object named 'var data;' that includes HTML content. Inside the content, there is a table with the id of 'table123'. The task at hand is to replace all instances of the word 'sample' wit ...