Add callback function to tailwind "duration" animation

21 Views Asked by At

I am using Tailwind CSS. What I want to do is have a DIV fade in on the page, then when the fade is complete, immediately fade out again. This is what I have

    <div class="duration-500 opacity-0" id="myDiv">
        My DIV
    </div>

Here is my javascript

    export cost myDiv = {
        component: null,

        init: function() {
            const _ = this;

            _.msgDiv = document.getElementById('myDiv');

            _.flashMessage(flashMessage)
        },

        flashMessage(callback = false)
        {
            const _ = this;

            _.myDiv.classList.toggle('opacity-0');

            if(callback)
            {
                callback();
            }
        }
    }

    myDiv.init();

This has two problems

  • Firstly, the class toggling is happening instantly on the callback. I need to fire the callback when the fade has completed, not when the class name has been toggled.
  • When the callback is fired, I get an error saying Cannot read properties of undefined (reading 'myDiv'). Why is myDiv available on the original fire, but not on the callback?

Thanks

1

There are 1 best solutions below

0
Typhoon101 On

I worked out an answer. It abandoned the idea of a callback altogether and instead used the transitionend event listener

    export cost myDiv = {
        component: null,

        init: function() {
            const _ = this;

            _.msgDiv = document.getElementById('myDiv');

            _.flashMessage()
        },

        flashMessage(callback = false)
        {
            const _ = this;

            _.myDiv.addEventListener('transitionend', () =>
            {
                _.myDiv.classList.add('opacity-0');
            }

            _.myDiv.classList.remove('opacity-0');
    }

    myDiv.init();