I am trying to make a dynamic function onClick which will change the color of the string, but color won't change, same function works if I call consol.log
const heading = document.getElementById('Hello')
function addStyleTo(node, text, color, fontSize) {
node.textContent = text
node.style.color = color
node.style.textAlign = 'center'
node.style.backgroundColor = 'black'
node.style.padding = '2rem'
node.style.fontSize = fontSize
}
setTimeout(() => {
addStyleTo(heading, 'Hello', 'red', '3rem')
}, 1000);
heading.onclick = () => {
if (heading.style.color === 'red') {
heading.style.color === 'pink'
} else {
heading.style.color === 'red'
}
You are using wrong the strict equality (===) and misses a curly brace.
Your code should be:
const heading = document.getElementById('Hello')
function addStyleTo(node, text, color, fontSize) {
node.textContent = text
node.style.color = color
node.style.textAlign = 'center'
node.style.backgroundColor = 'black'
node.style.padding = '2rem'
node.style.fontSize = fontSize
}
setTimeout(() => {
addStyleTo(heading, 'Hello', 'red', '3rem')
}, 1000);
heading.onclick = () => {
if (heading.style.color == 'red') {
heading.style.color = 'pink'
} else {
heading.style.color = 'red'
}
}
Here is a fiddle https://jsfiddle.net/tghcrzum/