Home > Enterprise >  Toggle image source with vanilla javascript function
Toggle image source with vanilla javascript function

Time:03-06

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

CodePudding user response:

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';
    }
})

CodePudding user response:

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;
    }
  }
}

CodePudding user response:

This code works :-

let replaced = false;

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

This uses a variable to keep track of whether or not the content was replaced on an alternate basis, if that makes any sense. Then based on that, it changes the source file of the images.

CodePudding user response:

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 ></div>

  • Related