I'm working on a web component and have a trouble hooking up JS function that randomizes colors. What I have achieved so far is different styles for global DOM and shadow DOM <h3> element (sentence 1, and sentence 2 repsectively). What I need is the shadow DOM <h3> element to be applied random colors from the array that sits in changeColor() function. Any ideas on how I can incorporate the function into the shadow DOM?
const template = document.createElement('template');
template.innerHTML = `
<style>
h3 {
color: coral;
}
</style>
<h3>Sentence 2 </h3>
`;
class UserCard extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
};
window.customElements.define('user-card', UserCard);
function changeColor() {
let num = 0;
let arr = ['#FFD640;', '#fdff76', '#f0cd59', '#fa9624', '#fa6824', '#a33f11'];
window.setInterval(function () {
num = (num + 1) % 4;
document.querySelector('h3').style.color = arr[Math.floor(Math.random() * arr.length)];
}, 1000);
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Components Example</title>
</head>
<body>
<h3>Sentence 1</h3>
<user-card>
<script src="userCard.js"></script>
</user-card>
</body>
</html>
changeColorfunction? It sounds as if you wantchangeColoras an additional method inside the class body. If you then change thesetTimeoutcallback to an arrow function, changedocument.querySelector('h3')tothis.shadowRoot.querySelector('h3'), and, inside theconstructor, callthis.changeColor();, is this what you want the code to do?arr=[...]andthis.shadowRoot.querySelector('h3').style.color = arr[Math.floor(Math.random() * arr.length)];right into the constructor, but it didn't give me any automation in terms of colors. I still have to manually reload the page to change the color