Help with my calculator

Help with my calculator
0

#1

I have my calculator project finished for the most part. Here’s what I have so far:

One of the issues I’m having is with the buttons. For the buttons to work you have to click precisely on the number/symbol, clicking the outer parts of the button won’t work. I think this is because in my javascript file I am targeting the span tag via

var elem = document.querySelectorAll(".button2");

I would like to target the entire button by targeting the div element the span is inside, but I can’t target the div with the querySelectorAll() function i.e. passing “button” (which is the div’s class) doesn’t work:

var elem = document.querySelectorAll(".button");

How do I target a div with querySelectorAll? Or do I need to use a different function for that?


#2

Try:

document.querySelectorAll(".button");

#3

I’m not sure what you mean by that. It works fine for me. Like Dawson says, just make that change.


#4

I would suggest to have a button tag for each number instead of div, and then you can target button.number1 for example


#5

I cleaned up some duplicate code and below is one possibility if you use the original suggestion I showed of

document.querySelectorAll(".button");

Below is my revision of your original code. Note the creation of a new variable called currChar which is used throughout the if then else part. I targeted the second child element childNodes[1] of each button class.

window.onload=function(){
  var elem = document.querySelectorAll(".button");
  var display = document.getElementById("displayText");
  var result = "";
  for(var i = 0; i < elem.length; i++){
    elem[i].addEventListener("click",function(){
      var currChar = this.childNodes[1].innerHTML;
      if(this.childNodes[1].innerHTML=='='){
        result = eval(display.innerHTML);
      }else if(currChar !== 'CE'){
        result += currChar;      
      }
      display.innerHTML = result;
    });
  }
};

NOTE: This revision does not solve the problems you are going to have using EVAL, but at least let’s you see how to grab the values from the keys.


#6

What I mean is if I try to target “.button” with querySelectorAll it doesn’t work.

I think this is because the span tag within the div is a child element and I’m not targeting it. Do I need to target it with the .childNodes[] function?


#7

Sorry, for JQuery I think it would be this:

  var elem = $(".button");

Though, it JQuery I often see it labeled like:

  var $elem = $(".button");

so you remember that $elem is a JQuery selector. It’s optional, but if you do it you’d have to change other references to that variable too.

Does that not work for you? It works for me when I plug it into your code. (After I add JQuery in the settings/Javascript/quick-add)


#8

@Nicknyr - If you look at the code I posted above, it shows how you can target the child node of each button.