Miroslav Savovski's solution works but they did not explain why, so I thought I would add this answer with the reasoning behind that and a step-by-step of how it is actually working, and why the OP's solution was not working initially.
TLDR? Scroll to the last two code snippets.
With template literals when you put a function inside of them it executes that function, so let's say we have a simple function like this that just returns a string of 'blue'
:
const getBlueColor = () => 'blue'
And then we call this function inside of a template literal like this:
`The color is ${getBlueColor()}`
What happens is that the getBlueColor()
is called right when that code is executed.
Now lets say we wanted to do this onclick
instead like this:
<button onclick="${getBlueColor()}"></button>
What is happening is that getBlueColor
is not being executed onclick
, it's actually executed when the template literal is executed.
The way we fix this is to prevent the template literal from executing this function by simply removing the template literal:
<button onclick="getBlueColor()"></button>
But now let's say you want to pass in some parameters to a function like getOppositeColor(color)
like this:
<button onclick="getOppositeColor(color)"></button>
This will not work because color
won't be defined. So you need to wrap that with a template literal and in a string like this:
<button onclick="getOppositeColor('${color}')"><button>
Now with this you will be calling the onclick
when the user clicks the button, and you will be passing it a string of the color
like this:
getOppositeColor('blue')