Skip to content

Commit

Permalink
Refactor all the querySelectors to one function
Browse files Browse the repository at this point in the history
  • Loading branch information
zalbright90 committed Jul 16, 2024
1 parent 73ff692 commit f65bbf4
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,15 @@ document.addEventListener('DOMContentLoaded', function() {
}
}

function bindButtonEvents(className, callback) {
const button = document.querySelector(`.${className}`);
if (button) {
button.addEventListener('click', callback);
}
}

['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'].forEach((className, index) => {
document.querySelector(`.${className}`).addEventListener('click', () => updateDisplay(index.toString()));
bindButtonEvents (className, () => updateDisplay(index.toString()));
});

[
Expand All @@ -123,28 +130,21 @@ document.addEventListener('DOMContentLoaded', function() {
{ op: '*', className: 'multiply' },
{ op: '/', className: 'divide' }
].forEach(({ op, className }) => {
const operatorChoice = document.querySelector(`.${className}`);
operatorChoice.addEventListener('click', () => setOperator(op));
bindButtonEvents(className, () => setOperator(op));
});

const dotButton = document.querySelector('.dot')
dotButton.addEventListener('click', () => {
if (!displayValue.includes('.')) {
bindButtonEvents('dot', () => {
if(!displayValue.includes('.')) {
updateDisplay('.');
}
});

document.querySelector('.clear').addEventListener('click', clearDisplay);
document.querySelector('.toggle-sign').addEventListener('click', toggleSign);
document.querySelector('.backspace').addEventListener('click', backspace);
document.querySelector('.percent').addEventListener('click', percent);
bindButtonEvents('clear', clearDisplay);
bindButtonEvents('toggle-sign', toggleSign);
bindButtonEvents('backspace', backspace);
bindButtonEvents('percent', percent);

const equalsButton = document.querySelector('.equals');
if (equalsButton) {
equalsButton.addEventListener('click', () => {
calculate();
});
};
bindButtonEvents('equals', calculate);

const numpadKeyMap = {
'Numpad0': '0',
Expand Down

0 comments on commit f65bbf4

Please sign in to comment.