What is the best way to insert a JavaScript button before an HTML button on a webpage?

Currently, I am working on creating a calculator using JavaScript and HTML. My goal is to add memory buttons (MS, MC, MR) before the clear button (C) on the calculator interface. Despite trying various methods, I am facing some challenges in achieving this desired arrangement.

I attempted to utilize the insertBefore() method, but I believe my approach may be incorrect. Any guidance or suggestions on how to properly insert the memory buttons before the clear button would be greatly appreciated.

Below is the section of JavaScript code where I encountered an issue:

//3.
//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"

//Changing font color of numbers to blue
const numbers = document.querySelectorAll('.number')
numbers.forEach(number => {
    number.style.color ="blue";
});

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

Here is a snippet of the HTML code:

<!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 Project </title>
 <script src="script.js" defer></script>
 <link rel="stylesheet" href="styles.css">

</head>

<body>
 <section class="calculator">
    <h1> My Calculator </h1>
  <form>
   <input type="text" name="" id="" class="display">
  </form>
  <div class="buttons"> 
   <!-- Memory buttons -->
   <button id="memoryStore" type="button" class="memory-btn">MS</button>
   <button id="memoryClear" type="button" class="memory-btn">MC</button>
   <button id="memoryRestore" type="button" class="memory-btn">MR</button>
   <!-- Other buttons -->
   <button id="clear" type="button" class="btn">C</button>
   <button id="add" type="button" class="btn">+</button>
   <button id="subtract" type="button" class="btn">-</button>
   <button id="multiply" type="button" class="btn">*</button>
   <button id="divide" type="button" class="btn">/</button>
   <button id="equals" type="button" class="btn">=</button>
  </div>

 </section>

</body>

</html>

Answer №1

To start off, you can utilize the before() method on the clear button by adding a new button before it. Then, as you continue to add elements, you can add the new ones before the existing ones. Here's an example:

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

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

// Lastly, insert the `memoryRestoreButton` before `memoryClearButton`
var memoryRestoreButton = document.createElement("BUTTON");
memoryRestoreButton.innerHTML = "MR";
memoryClearButton.before(memoryRestoreButton);

//3.
//Changing colors of operation buttons

//Adjusting Multiply button color
const colorMultiply = document.getElementById("multiply");
colorMultiply.style.backgroundColor = "green";

//Adjusting Divide button color
const colorDivide = document.getElementById("divide");
colorDivide.style.backgroundColor = "red";

//Adjusting Subtract button color
const colorSubtract = document.getElementById("subtract");
colorSubtract.style.backgroundColor = "blue";

//Adjusting Add button color
const colorAdd = document.getElementById("add");
colorAdd.style.backgroundColor = "yellow";

//Changing font color of numbers to blue
const numbers = document.querySelectorAll(".number");
numbers.forEach(number => {
  number.style.color = "blue";
});

//Changing 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";
clearButton.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);
<h1>Calculator 8</h1>
<form>
  <input type="text" name="" id="" 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 class="number" id="number9" type="button" class="btn8 btn-grey" data-num="9">
        9
      </button>
  <button class="number" id="number8" type="button" class="btn8 btn-grey" data-num="8">
        8
      </button>
  <button class="number" id="number7" type="button" class="btn8 btn-grey" data-num="7">
        7
      </button>
  <button class="number" id="number6" type="button" class="btn8 btn-grey" data-num="6">
        6
      </button>
  <button class="number" id="number5" type="button" class="btn8 btn-grey" data-num="5">
        5
      </button>
  <button class="number" id="number4" type="button" class="btn8 btn-grey" data-num="4">
        4
      </button>
  <button class="number" id="number3" type="button" class="btn8 btn-grey" data-num="3">
        3
      </button>
  <button class="number" id="number2" type="button" class="btn8 btn-grey" data-num="2">
        2
      </button>
  <button class="number" id="number1" type="button" class="btn8 btn-grey" data-num="1">
        1
      </button>
  <button class="number" 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>

The ChildNode.before() method allows you to insert a set of Node or DOMString objects in the children list of this ChildNode's parent, just before this ChildNode. DOMString objects are inserted as equivalent Text nodes.

Answer №2

Have you considered dynamically inserting buttons? Perhaps you are looking to toggle expanded controls.

Implementing this with JavaScript can be challenging.

Instead, include all HTML buttons and use CSS to control the visibility of the buttons you wish to toggle.

Utilize JavaScript to toggle the CSS class on the container.

<button id="mc" type="button" class="btn8 btn-grey advanced">MC</button>
.calculator8 .advanced { display: none; }
.calculator8.showAdvanced .advanced { display: block; }
document.querySelector('.calulator8').classList.toggle("showAdvanced")

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

Iconic Navigation: Bootstrap 3 Navbar featuring Carousel

I'm currently in the process of developing a website using bootstrap3. Despite watching numerous tutorial videos, I am still facing challenges. One of my goals is to have the logo on the navbar aligning with the left side (which I've achieved ...

Using AJAX to pass post variables

Here is a link I have: <a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a"> This link triggers an ajax call. $(".tag").click(function() { var for_user_id = $(this).attr("for_user_id"); var wl_id = $(this).attr("wl_ ...

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

Instructions for submitting information from a web form using Python without needing to know the form's ID or name

I am currently attempting to automate the submission of data into the online forms found on this webpage: Unfortunately, I am unable to determine the specific names of these forms by inspecting the source code. I have tried using the requests python modul ...

invoking a parent function from a cellRenderer in Vue.js Ag-Grid through emit function

I integrated the ag-grid-vue into my project and added a separate component to one of the columns for user actions, such as Edit, View, or Delete. Editing and deleting records work fine, but when a record is deleted, I want the table to re-render by fetchi ...

The Vuetify v-img component is failing to render on the screen

I am facing an issue with this code snippet as the image is not being displayed. I have double-checked the path to the image and everything seems to be correct. I am unable to figure out what the problem is, as everything looks clear in the console. <v- ...

Issue with Silverlight HyperlinkButton in DataGrid column requiring double-click to activate

I've encountered an issue with a datagrid column that contains Hyperlinkbuttons. Strangely, I have to click the button twice in order for it to perform its intended action. My theory is that the first click is somehow selecting the row instead of trig ...

Transform the dataUrl into a blob and send it via ajax request

I am currently utilizing the imgly image cropper plugin with some modifications for my application. It has the ability to convert an image into a dataUrl and produce the image as a base64 image which can then be saved as a jpeg. My objective is to adjust ...

Displaying Edit and Delete options upon hovering over the data row

I'm working on a table that uses ng-repeat on the <tr> element. In the last column of each row, I have edit/delete links that should only be visible when the user hovers over the <tr> element. <tr ng-repeat="form in allData | filter:se ...

Achieving vertical centering by adjusting padding within the parent container

I've successfully set up a DIV with a height of 200px and an inner div at 150px, leaving me 50px for the image caption. Now I want to vertically center the text within that remaining 50px. .captioned { width: 300px; height: 200px; display: fl ...

The Azure SpeechSynthesizer encountered an error due to using HTTP instead of the expected HTTPS protocol. This issue can be resolved by installing the NPM package `microsoft

Recently, I have been encountering an issue with the microsoft-congnitiveservices-speech-sdk npm package. Everything was working smoothly until randomly an error started popping up. This could be due to a browser update or a minor package update - I'm ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

Issue with Three.js: The mouse hover effect does not revert back to the previous color

Currently, I am working on creating a pattern using Three.js. The goal is to change the color of a face to gray when the user hovers over it with the mouse, and then revert it back to its original light blue color when the mouse moves away. Unfortunately, ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Having trouble with Node.js and jQuery on my local machine

My Node.js API is designed to create a post with simplicity: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var app = express(); var Posts = require('./mode ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

Challenges in customizing the bootstrap navigation bar links

Having an issue with the bootstrap navbar link displaying on small devices. Here is the template I'm using: https://i.sstatic.net/jSy1b.png The last item is displaying in two lines. ...

Establishing the folder organization for Express Handlebars

I work with NodeJs, Express, and Handlebars. The main file for my server is named app.js const express = require('express'); const exphbs = require('express-handlebars'); const app = express(); app.engine('handlebars', ex ...