I would like to apply the toggle function I have in line 42 of the attached pen to each of the groups of buttons on the right hand sides of my page (the function is just working for the very first button at the moment). I did try it for a few more of the consecutive button by adding the onclick function to those and including a loop (see bottom of JS code), but I saw some unexpected results (like every single button turning green).
Would someone be able to set me off in the right direction with this please?
Alright, try making differant functions, for example:
<button onclick="toggle1()" id="button-1">toggle this button</button>
<button onclick="toggle2()" id="button-2">toggle this button</button>
<script>
function toggle1() {
// code to determine whether the button was clicked previously
}
// same thing as toggle1() here
</script>
that is a building block/example, if it is not correct or you want me to do the data items let me know
What I was actually wondering though is if it’s somehow possible to apply the same toggle function to the buttons rather than giving them all different names (and functions, since there are so many), e.g. by using a loop and a shared class name…
function changeColor(event) {
// in here, event.target is the button clicked, you can change the color of that element
event.target.classList.toggle('greenButton')
}
buttons.forEach(button => button.addEventListener('click', changeColor))
Many thanks, I am currently trying this but I think I am a bit confused.
In my case I have numerous pomodoro buttons all with a class of ‘pomodoro-btn’ and IDs of ‘pomodoro-btn-1’ etc., but in the changeColor function above, I need to target an individual button (by ID say), so would that not affect things when it’s called in the next piece of code?
Applying the code you gave, this would give:
function changeColor("click") {
let pomodoroButton1 = document.querySelector("#pomodoro-btn-1");
pomodoroButton1.classList.toggle("greenColor");
}
let pomodoroButtons = document.querySelectorAll(".pomodoro-btn");
pomodoroButtons.forEach((pomodoroButton) => pomodoroButton.addEventListener("click", changeColor));
I know I am missing something fundamental in my understanding of this, but if I am targeting a specific button in the first piece of code, how can that work if that same code is then called for all the other buttons when the function is called in the second piece of code?
I hope the way I have phrased it makes (some) sense
ok, thanks. I thought I had to substitute values in for event and target and did not realise that ‘event.target’ itself was a property. I clearly need to read more around this topic, but thanks for the help, it’s all working as hoped now.