I have a star icon from Google. I made it into a button. When it is clicked, I’d like it to have a fill color. I am able to do such when I use javascript and an event listener. However, if I add an if else
to the event listener, it no longer works. Any help?
const star = document.getElementById('star');
star.addEventListener('click', () => {
if (star.style.fontVariationSettings === "'FILL' 0") {
star.style.fontVariationSettings = "'FILL' 10";
} else {
star.style.fontVariationSettings = "'FILL' 0";
}
});
.star {
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24
}
.star {
background: none;
border: none;
color: var(--check-color);
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="star" class="material-symbols-outlined star">star</button>
</body>
<script src="myscript.js"></script>
</html>
I was expecting the if else statement to work properly.
2
Answers
The style setting is being canonicalized after you assign it, and it’s using double quotes rather than single quotes.
Instead of assigning to the style, it would be better to use a class that you toggle.
It’s not the
if
. It’s yourbackground: none;
that preventsfontVariationSettings
from working.