Home > Enterprise >  Why am I not able to add a space to the end of this string in my DOM?
Why am I not able to add a space to the end of this string in my DOM?

Time:11-05

I am trying to build a calculator readout display. Must show characters appearing as the user presses buttons.
GOAL: I want there to be a space before AND after my sign. EX: 97 78
PROBLEM: My sign only appears with a space on the left side, but not the right side. EX: 97 78

I am currently executing this with a function called addToDisplay().
As you can see in my code, I have tried adding the spaces in strings and tried even writing an if-statement to add a space in front if the user has not typed a number in yet.
(Sure, I could probably just ALWAYS have a space to appear, but I don't want numbers that are part of the same int (example: 194 != 1 9 4) to have spaces between them,
but I would like there to be even whitespace between the sign and my numbers on the display. (full switch block omitted for readability)

link to full code here

function addToDisplay (string){
  //adds the passed in string to the end of the display readout
  let display = document.querySelector("#display");
  //get the current string that is displayed with .innerText
  let currentDisplay = display.innerText;
  display.style.color = "red";
  //add the new string to the old string
  if (currentNumber == undefined){
    display.innerText = currentDisplay   "  "   string;
  } else{
  display.innerText = currentDisplay   ""   string;
    }
}

const onClick = function() {
switch (this.id){
  case "plus":
    alert("plus sign pressed");
    clearCurrentNumber();
    addToDisplay("  _");
    
    break;

document.getElementById('plus').onclick = onClick;

CodePudding user response:

By default, when you append " " to the innerText of a div, the last space is ignored. To preserve the trailing white space, use white-space: pre.

#display{
  white-space: pre;
}

As a side note, the code in addToDisplay() can be shortened as follows:

function addToDisplay (string){
  //adds the passed in string to the end of the display readout
  let display = document.querySelector("#display");
  display.style.color = "red";
  //add the new string to the old string
  display.innerText  = string;
}
...

    addToDisplay("   "); //line 190

  • Related