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

206
Visualizações
How to change a background url of css in javascript?

Below is my css code, I wanna change the url background via javascript, maybe adding it to a variable because the url will be changing depeding on some cases in my program. How do I do this? Thanks :)

body {
    width: 100vw;
    height: 100vh;
    background: url('exampleurl.com/example');
    background-color: #02203b;

    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    align-items: center;
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use backgroundImage like:

const url = 'https://via.placeholder.com/500';
document.body.style.backgroundImage = `url(${url})`;
body {
    width: 100vw;
    height: 100vh;
    background: url('exampleurl.com/example'); /* you can use that as default */
    background-color: #02203b;

    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    align-items: center;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Good way to achieve this would be to use the JS classList function. https://developer.mozilla.org/de/docs/Web/API/Element/classList

function change() {
  const b = document.querySelector('body');
  b.classList.toggle('dark');
}
body {
    width: 100vw;
    height: 100vh;
    background: url('exampleurl.com/example');
    background-color: #02203b;

    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    align-items: center;
}

.dark {
  background: black; 
  background: url('https://via.placeholder.com/500/green');
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;  
}
<button onclick="change()">change</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

To change it with jquery use :

const url = 'https://via.placeholder.com/500';
$('body').css('background-image', 'url($url)');

That is if you want to change it on conditions, etc

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