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

273
Visualizações
Toggle image source with vanilla javascript function

I am trying to swap an SVG logo image on click using Javascript. My script looks like this:

document.querySelector('.logo').addEventListener('click', function() {
    document.querySelector('#logo-switch').src='logo-B.svg';
    document.querySelector('#logo-switch').src='logo-A.svg';
    })

The function works on the first click (when the third line of code is removed): document.querySelector('#logo-switch').src='logo-A.svg';

However, I would like for it to switch back to the original src each time the logo is clicked — this should function as a toggle.

Is this done with an if statement? Or how is this achieved?

Many thanks

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

0

Use an extra css-class for the .logo element and toggle that on click. The snippet is using event delegation for that.

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.classList.contains(`logo`)) {
    return evt.target.classList.toggle(`right`);
  }
}
.logo {
  width: 150px;
  height: 150px;
  display: inline-block;
  background: url(//upload.wikimedia.org/wikipedia/commons/a/af/Skip_to_left3.svg) no-repeat;
  background-size: contain;
  cursor: pointer;
}

.right {
  background-image: url(//upload.wikimedia.org/wikipedia/commons/1/1f/Skip_to_right3.svg);
}
<div class="logo"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You need checks to see which logo is current and then replace it with another one. It can also be done via ternary operators, but if-else is more human-readable/understandable in this case.

As in OP you described the function works well on first click, so assuming the click handler is working fine, here is the condition below to add

document.querySelector('.logo').addEventListener('click', function() {
    if (document.querySelector('#logo-switch').src.indexOf('logo-A') != -1) {
      document.querySelector('#logo-switch').src = 'logo-B.svg';
    } else {
      document.querySelector('#logo-switch').src = 'logo-A.svg';
    }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

How about using a closure?

document.querySelector('.logo').addEventListener(
  'click',
  switchImage(
    document.querySelector('#logo-switch'),
    'logo-B.svg',
    'logo-A.svg'
  )
);

function switchImage (element, src1, src2) {
  var first = true;
  return function () {
    if (first) {
      element.src = src1;
      first = false;
    } else {
      element.src = src2;
      first = true;
    }
  }
}

EDIT: using the snippet from @kooiinc

document.querySelector('.logo').addEventListener(
  'click',
  switchImage(
    document.querySelector('#logo-switch'),
    '//upload.wikimedia.org/wikipedia/commons/1/1f/Skip_to_right3.svg',
    '//upload.wikimedia.org/wikipedia/commons/a/af/Skip_to_left3.svg'
  )
);

function switchImage (element, src1, src2) {
  var first = true;
  return function () {
    if (first) {
      element.setAttribute('href', src1);
      first = false;
    } else {
      element.setAttribute('href', src2);
      first = true;
    }
  }
}
.logo,
#logo-switch {
  width: 150px;
  height: 150px;
  display: inline-block;
  cursor: pointer;
}
<svg class="logo">
  <image id="logo-switch" href="//upload.wikimedia.org/wikipedia/commons/a/af/Skip_to_left3.svg">
</svg>

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