I am still fairly new to JavaScript and am trying to deepen my understanding of it through mini projects.
In this counter project, I have managed to get the result what I want:
- After clicking the "add" button, the counter increment would increase and change color to green.
- After clicking the "subtract" button, the counter increment would decrease and change color to red.
Below would be my JavaScript code:
//create variables to hold the HTML selectors
var counterDisplay = document.querySelector('.counter-display');
var counterMinus = document.querySelector('.counter-minus');
var counterPlus = document.querySelector('.counter-plus');
//create variable for the counter
//what we'll use to add and subtract from
var count = 0;
//create a function to avoid code redundancy
function updateDisplay(){
counterDisplay.innerHTML = count;
};
function toGreen(){
document.querySelector('.counter-display').style.color = "green";
};
function toRed(){
document.querySelector('.counter-display').style.color = "red";
};
/*-------------------------------------------*/
updateDisplay();
//EventListeners
counterPlus.addEventListener("click", () =>{
count++;
updateDisplay();
toGreen();
});
counterMinus.addEventListener("click", () =>{
count--;
updateDisplay();
toRed();
});
I separated the color functions but I feel like there's a cleaner way to write this code i.e conditionals like if statements, however, as I'm still learning I don't fully know how to implement this.
**As mentioned, I'm still learning so a thorough explanation/laymen's terms is greatly appreciated!
Please let me know for any clarifications or if more info is needed!
Thank you in advance!
EDIT: Thank you those who have taken the time to help me in sharing their solutions!