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?
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.
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?