Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
Web components and JS functions

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>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I would shorten it to:

customElements.define('user-card', class extends HTMLElement {
  constructor() {
    super().attachShadow({mode:"open"})
           .innerHTML = "<style>h3{color:coral}</style><h3>Sentence 2 </h3>";
    let arr = ['#FFD640;', '#fdff76', '#f0cd59', '#fa9624', '#fa6824', '#a33f11'];
    setInterval(() => {
      let newColor = arr[Math.floor(Math.random() * arr.length)];
      this.shadowRoot.querySelector('h3').style.color = newColor;
    }, 100);
  }
});
<user-card></user-card>

  • Separate class definition only required when you need to use it multiple times
  • super sets AND returns the 'this' scope, so you can chain on it
  • attachShadow sets AND returns this.shadowRoot, so you can chain on it
  • <templates> only make sense for more complex HTML, use .innerHTML for the easy stuff
  • You are storing the ID reference of setInterval in this.changeColor (required if you want to end the loop) But then you are calling it as a function... see: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
about 4 years ago · Juan Pablo Isaza Relatório

0

Another option would be to pass the context for the querySelector to changeColor, with document as the default if no context gets passed. This way changeColor becomes more flexible while also retaining backwards compatibility.

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));
        changeColor(this.shadowRoot);
    }
};

window.customElements.define('user-card', UserCard);


function changeColor(context = document) {
    let num = 0;
    let arr = ['#FFD640;', '#fdff76', '#f0cd59', '#fa9624', '#fa6824', '#a33f11'];
    window.setInterval(function () {
        num = (num + 1) % 4;
        context.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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Define the colors in the class as a property. Create a function or a getter for retrieving the h3 element from the Shadow DOM for easy access.

Custom Elements have lifecycles, meaning that it has certain methods that will be called at certain points in time depending on the context. connectedCallback will be called when the element is placed inside the main DOM and will ensure that your component is rendered and ready. In there call your setInterval logic. Change the function() declaration to an arrow function () => to ensure that the this keyword points at the component.

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));
  }
  
  colors = ['#FFD640', '#fdff76', '#f0cd59', '#fa9624', '#fa6824', '#a33f11'];

  get heading() {
    return this.shadowRoot.querySelector('h3');
  }

  connectedCallback() {
    window.setInterval(() => {
      this.heading.style.color = this.colors[Math.floor(Math.random() * this.colors.length)];
    }, 1000);
  }
};

window.customElements.define('user-card', UserCard);
<!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></user-card>
  <script src="userCard.js"></script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda