Skip to content
Advertisement

How do I construct a click event from fixed part into a dynamic/variable part? (Vanilla JS)

I have a simple CSS3 Flipbox which I’m trying to re-use multiple times. The best would be if each element has a unique ID, and each of them would be separately triggered on click.

At the moment all the elements are being triggered on click.

What would be the best approach without just doubling the code?

Here demo of the code:

https://codepen.io/baidoc/pen/LYeqwxe

let cardTransitionTime = 500;

let $card = $('.card');
let switching = false;

$('.card').click(flipCard);

function flipCard() {
  if (switching) {
    return false;
  }
  switching = true;

  $card.toggleClass('is-switched');
  window.setTimeout(function () {
    $card.children().children().toggleClass('is-active');
    switching = false;
  }, cardTransitionTime / 2);
}

Advertisement

Answer

I havent thought your transitionTime example through and left it out in a more simplified example, but for the other part you can simply use the event argument which is handed over to your called function per default:

$('.card').click(flipCard);

function flipCard(ev) {
  ev.currentTarget.classList.toggle('is-switched');
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement