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

208
Visualizações
Changing :before value on button click CSS style and Javascript

I'm having some trouble changing the color of :before on a button click event. At the moment, I've got code which changes the background to red when I call the changeColor(); function but doesn't change the :before section which is the "tick" on a chat bubble I'm coding. Any ideas what I'm doing wrong?

Please see the code below:

HTML:
<p id="chatLog"></p>

CSS:
body {
background: #368dda;
}

.p {
position: relative;
font-family: sans-serif;
font-size: 18px;
line-height: 24px;
width: 300px;
background: #fff;
border-radius: 40px;
padding: 24px;
text-align: center;
color: #000;
}

.p:before {
 content: "";
 width: 0px;
 height: 0px;
 position: absolute;
 border-left: 24px solid #fff;
 border-right: 12px solid transparent;
 border-top: 12px solid #fff;
 border-bottom: 20px solid transparent;
 left: 32px;
  bottom: -24px;
}

Javascript:
function changeColor() {
document.getElementById('chatLog').style.backgroundColor = `red`;
return false;     
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Javascript has access to the DOM, but a pseudo element is generated by the css. You'd need to instead just toggle an additional css class to overwrite the original pseudo attributes attached to the element that supplies the pseudo as such.

doStuff = () => {
  const example = document.getElementById('special-p');
  example.classList.toggle('green-before');
}
p {
  font-size: 1rem;
  color: #fff;
  position: relative;
  padding: 1rem;
  outline: gray 1px dotted;
}

p:before {
  content: '';
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: #f00;
  z-index: -1;
  transition: background-color .5s ease;
}

.green-before {
  color: #000;
}
.green-before:before {
  background-color: #0f0;
}
<p id="special-p">The lazy brown dog jumps over the fence.</p>

<button onclick="doStuff()">Do Stuff</button>

You can also look at background: inherit to allow the pseudo's to inherit attributes by the parent.

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