Search code examples
javascriptjqueryanimationthisanime.js

How can I target $(this) in anime.js


I am trying to achieve a click animation on a <a> tag. There are multiple <a> tags and all of them have the same class.

How do I achieve this?

As an alternative, I had tried adding a class as temporary to the targeted element using $(this).addClass('temp')

I need to know if there is a better way to actually do it.

If I go with the above method, I won't be able to bring animations with delays.

Sample

<script>
  $("a").click(function(){
    anime({
    targets:'a',
    opacity:[0,1],
    })
  });
</script>


Solution

  • You can simply pass e.currentTarget to the targets property (which accepts a DOM node), so that you will target the current <a> element that the event listener is bound to. Alternatively you can also pass in this: it's up to you.

    See proof-of-concept below. I have tweaked the opacity to 0.25 so that you can actually see the element before clicking on it.

    $("a").click(function(e) {
      e.preventDefault();
      anime({
        targets: e.currentTarget,
        opacity: [0.25, 1],
      })
    });
    a {
      opacity: 0.25;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>

    Or just do it natively in JS without needing jQuery:

    document.querySelectorAll('a').forEach(el => {
      el.addEventListener('click', e => {
        e.preventDefault();
        anime({
          targets: el,
          opacity: [0.25, 1],
        });
      });
    });
    a {
      opacity: 0.25;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>
    <a href="#">Click me</a>