Storing a screen value with javascript made simple

I need to incorporate memory functions into my calculator, specifically MS (Memory Store), MR (Memory Restore), and MC (Memory Clear). For Memory Store, the screen value of the calculation needs to be saved, so if it's 90 + 7 = 97, that result should be stored. Then I should be able to recall that value using the MR button. And if I decide to clear the memory entirely, I can do so by clicking on MC.

Currently, I have a basic layout at the bottom of the code where I'm trying to create events for storing the number in a variable and then retrieving it when Memory Restore is clicked. However, when attempting to clear the memory by setting the variable to empty ("") nothing seems to work as expected.

JS:

//Changing colors of operation colors 

//Multiply Color
const colorMultiply = document.getElementById('multiply')
colorMultiply.style.backgroundColor = "green" //Makes Color Green

//Divide Color
const colorDivide = document.getElementById('divide')
colorDivide.style.backgroundColor = "red"//Makes Color Red

//subtract color
const colorSubtract = document.getElementById('subtract')
colorSubtract.style.backgroundColor="blue"//Makes Color Blue

//add color
const colorAdd = document.getElementById('add')
colorAdd.style.backgroundColor="yellow"//Makes Color Yellow


//change font of numbers to blue (I did it like this incase anyone wants to color of a single number)
//Makes it easier for you to change a colour of one button
const number1 = document.getElementById('number1')
number1.style.color="blue"
const number2 = document.getElementById('number2')
number2.style.color="blue"
const number3 = document.getElementById('number3')
number3.style.color="blue"
const number4 = document.getElementById('number4')
number4.style.color="blue"
const number5 = document.getElementById('number5')
number5.style.color="blue"
const number6 = document.getElementById('number6')
number6.style.color="blue"
const number7 = document.getElementById('number7')
number7.style.color="blue"
const number8 = document.getElementById('number8')
number8.style.color="blue"
const number9 = document.getElementById('number9')
number9.style.color="blue"
const number0 = document.getElementById('number0')
number0.style.color="blue"
const decimal = document.getElementById('decimal')
decimal.style.color="blue"

//Changing color of the clear button
const clear = document.getElementById('clear')
clear.style.color="white"
clear.style.backgroundColor="black"

///////////////////////////////////////////////////////////////////////////////////////////////////////
// Then we want to insert `memoryStoreButton` before the `clear` button:
var memoryStoreButton = document.createElement("BUTTON");
memoryStoreButton.innerHTML = "MS";
clear.before(memoryStoreButton); //puts button before clear

// Then we want the `memoryClearButton` before `memoryStoreButton`
var memoryClearButton = document.createElement("BUTTON");
memoryClearButton.innerHTML = "MC";
memoryStoreButton.before(memoryClearButton);//puts button before clear

// and finally, the `memoryRestoreButton` before `memoryClearButton`
var memoryRestoreButton = document.createElement("BUTTON");
memoryRestoreButton.innerHTML = "MR";
memoryClearButton.before(memoryRestoreButton);//puts button before clear

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//What number buttons are pressed
var numButton = document.querySelectorAll(".btn8");
var showNum = document.querySelector(".screen8");


numButton.forEach(function(button){
button.addEventListener('click', function(event){
if(event.target.innerHTML == "C"){
  return showNum.value = "";
} else if (event.target.innerHTML == "=") {
  return;
}
let view = event.target.dataset.num;
showNum.value += view;
});
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//When equal is pressed it calculates the numbers, and if no numbers were entered there will be an error message
var equalButton = document.querySelector("#equals")
equalButton.addEventListener('click', function(event){
if(showNum.value == ""){
  return alert("Please Enter a Value"); // If no numbers are being displayed, error alert.
}
showNum.value = showNum.value + "=" + eval(showNum.value);
});

//Align text to the right of the screen
document.getElementById("numberBox").style.textAlign = "right";
////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Change colors when hovering over buttons
var btn = document.getElementsByTagName("button")
function addButtonHandlers(btn) {

// make black button on mouseover
btn.addEventListener('mouseover', () => {
btn.style.backgroundColor = 'black';
});

// make grey button on mouseout
btn.addEventListener('mouseout', () => {
btn.style.backgroundColor = 'grey';
});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Making a memory store button functional
memoryStoreButton.addEventListener('click',function(event){
var memoryStoreValue = (showNum.value)  
})

//Making memory Clear Button functional

//Making a memory Restore Button functional
memoryStoreButton.addEventListener('click',function(event){
showNum.memoryStoreValue
})

//Making memory Clear Button functional
memoryStoreButton.addEventListener('click',function(event){
memoryStoreValue= ""
})

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">

<title> Calculator 8 </title>
 <script src="fp.js" defer></script>
 <link rel="stylesheet" href="fp.css">

</head>
<body>
 <section class="calculator8">
    <h1> Calculator 8 </h1>
  <form>
   <input type="text" name="calcScreeng" 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>
</body>
</html>

CSS:


*{
 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: 5rem;
 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-kground: rgb(224,224,224);
}

.btn8{
 font-size: 4rem;
}

Answer №1

an easy way to store data is by using localStorage

To Save Data:

localStorage.setItem("score", 100); // or localStorage.score = 100;

To Retrieve Data:

localStorage.getItem("score") // or localStorage.score;

To Clear Data:

localStorage.setItem("score", ""); // or localStorage.score = "";

Answer №2

There are numerous ways to accomplish that goal.

I suggest starting by storing the data in the DOM using a button.

This method may seem simple, but it is beneficial for learning purposes because you can easily view the stored value in your debugger by inspecting the element.

memoryRestoreButton.onclick = (function(){
  // Store the value
  memoryRestoreButton.dataset.whatever = numberBox.value
  // Read the stored value
  console.log(memoryRestoreButton.dataset.whatever)
})
<button id="memoryRestoreButton">MR</button>
<input id="numberBox" value="8888">

The element now has a new attribute data-whatever, allowing you to access the value from anywhere in your code.

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


Your code has been modified. The calculator is not functioning properly due to a missing library that was not included. Additionally, your code employs the use of eval() for calculations, which is considered insecure. It is recommended to use New Function() instead. If this is an old exercise, it may be worthwhile to bring it up with your teacher.

//Changing colors of operation buttons 

//Multiply Color
const colorMultiply = document.getElementById('multiply')
colorMultiply.style.backgroundColor = "green"

//Divide Color
const colorDivide = document.getElementById('divide')
colorDivide.style.backgroundColor = "red"

//Subtract Color
const colorSubtract = document.getElementById('subtract')
colorSubtract.style.backgroundColor = "blue"

//Add Color
const colorAdd = document.getElementById('add')
colorAdd.style.backgroundColor = "yellow"

//Change font color of numbers to blue
const numberButtons = document.querySelectorAll('.btn8');
numberButtons.forEach(button => {
  button.style.color = "blue";
});

//Change color of the clear button
const clearButton = document.getElementById('clear');
clearButton.style.color = "white";
clearButton.style.backgroundColor = "black";

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

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

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

///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Define functionality for number buttons pressed
var numButtons = document.querySelectorAll(".btn8");
var displayScreen = document.querySelector(".screen8");

numButtons.forEach(function(button){
  button.addEventListener('click', function(event){
    if(event.target.innerHTML === "C"){
      return showNum.value = "";
    } else if (event.target.innerHTML === "=") {
      return;
    }
    let view = event.target.dataset.num;
    showNum.value += view;
  });
});

///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Calculate numbers when equals button is pressed, display error message if no numbers entered
var equalButton = document.querySelector("#equals")
equalButton.addEventListener('click', function(event){
  if(displayScreen.value === ""){
    return alert("Please Enter a Value");
  }
  displayScreen.value = displayScreen.value + "=" + eval(displayScreen.value);
});

//Align text to the right of the screen
document.getElementById("numberBox").style.textAlign = "right";

////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Change button colors on hover
var btns = document.getElementsByTagName("button")

function addButtonHandlers(btn) {

  // make black button on mouseover
  btn.addEventListener('mouseover', () => {
    btn.style.backgroundColor = 'black';
  });

  // make grey button on mouseout
  btn.addEventListener('mouseout', () => {
    btn.style.backgroundColor = 'grey';
  });
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////
let memoryValue = 0;

//Functionality for memory store button
memoryStoreButton.addEventListener('click', function(event){
  memoryValue = numberBox.value;
});

//Functionality for memory clear button
memoryClearButton.addEventListener('click', function(event){
  memoryValue = 0;
});

//Functionality for memory restore button
memoryRestoreButton.addEventListener('click', function(event){
  numberBox.value = memoryValue;
});
*{
 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: 5rem;
 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-kground: rgb(224,224,224);
}

.btn8{
 font-size: 4rem;
}
<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">

<title> Calculator 8 </title>

</head>
<body>
 <section class="calculator8">
    <h1> Calculator 8 </h1>
  <form>
   <input type="text" name="calcScreeng" 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>
</body>
</html>

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

Establishing the initial value for an input file form

Similar Question: Dynamically set value of a file input I'm currently working with an HTML form that includes a file input field, and I'm attempting to set the initial value for the file path in the form. I've tried changing the "value" ...

Minimize the use of globalized variables in your LESS CSS code

Is there a better way to avoid using globally diffused variables? I conducted a test with the following setup: _import.less @test: #FFF; _import2.less @test: #000; test.less @import (reference) "_import"; body { background: @test; } test2.less ...

``Maybe there is a way to fix the issue of jQuery not functioning properly

I am currently working on integrating jquery with Reactjs to add a class on click event. The functionality works fine when the page is refreshed, but it stops working if I navigate to the page after clicking on any menu item without refreshing. How can I ...

Tips for creating a hover effect on a rounded outline button with a gradient border

What I am looking for: I want the buttons to have rounded corners; The buttons should use linear-gradient, with button A as the border and button B as the background color; When hovering over the buttons, the opacity should change to 0.5. This works fine ...

JavaScript code for validating two passwords is malfunctioning

I'm currently working on a registration form for my website and I'm trying to implement a JS script that compares two password inputs (password and repeat password) and displays a message saying "passwords are not the same." Below is the code I h ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

nap within a for loop and executed in a finally block

I am currently facing a challenge with the following loop: for (const pk of likerpk) { await likeMediaId(ig, pk.trim()); } The problem is that I want to call likeMediaId every X seconds and then, after likeMediaId is done for all items, I want to c ...

Verify JSON data from server using AngularJS

My understanding is that in Angular, the HTTP service has two checks for 'success' and 'error' when connecting to a service. I have already handled these checks as my first step. The issue I am facing now is with the data in my JSON fi ...

Ways to deactivate a button with a designated identification through iteration using jQuery

Can't Figure out How to Deactivate a Button with Specific ID $('.likes-button').click(function(){ var el= this; var button1 = $(el).attr('id'); console.log(button1) $('#button1').attr("disabled",true); }) ...

What is the best way to initiate a page refresh from a separate component in ReactJS?

As a newcomer to React, I am facing an issue in my CRUD application. I have a Main component and in the List Component, I need to fetch data from the server using an API call. The problem arises when I submit a new item in the Create component - I have to ...

Viewport height-responsive image not functioning as expected in Firefox browser

Is there a way to set an image to the 100% height of the browser window, with a small padding at the bottom, and have it centered on the page? I created an example in codepen that works well in Chrome and Safari, but not in Firefox. In Firefox, the image ...

Obtain the date in the following format: 2016-01-01T00:00:00.000-00:00

Can someone help me convert this date to the correct format for the mercadolibre api? I need it to be like this: 2016-01-01T00:00:00.000-00:00 However, when I try with the following code: var date_from = new Date(); date_from.setDate(date_from.getDa ...

Navigating with Angular's router occurs before the guard is fully completed

Within my Angular 8 application, the routing file is structured as below: const myRoutes: Routes = [ {path: '', component: FirstComponent , canActivate: [RegistrationSrcdGuard]}, {path: 'FirstComponent ', component: FirstCompon ...

What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable t ...

Tutorial on creating a subset of a series using jqplot

I am looking to display three series on the same canvas. The series are defined as follows: rec1 = [0, 0, 150, 200, 0 ]; rec2 = [60, 120, 179, 240, 300]; rec3 = [50, 100, 150, 200, 250]; Below are the source codes I am using to draw these series. $ ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

Rearrange the sequence of specific child elements within the Div

Is there a way to reverse the order of specific div's children elements using just CSS? For instance: I need <div id="parent"> <a>A</a> <a>B</a> <a>C</a> <a>D</a> &l ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...