JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<div class="tile"></div>

CSS

.tile {
    height: 100px;
    width: 400px;
    background-color: blue;
    -webkit-transition: all 2s;
}

.tile.hover {
    height: 400px;
}

JavaScript

$(document).ready(function() {
    $(document.body).on('mouseenter mouseleave', '.tile', function(event) {
        var $this = $(this);
        if (event.type == 'mouseenter') {
            // update "hovering" state so we always know what the correct state should be
            $this.data("hovering", true);
            
            // if hover class not set, the set it and start the timer
            // if hover class already set, then nothing to do
            if (!$this.hasClass('hover')) {
                $this.addClass('hover');
                var timeout = setTimeout(function() {
                    // clear timer marker so we know transition has completed
                    $this.removeData("timer");
                    // update object to correct state if no longer hovering
                    // the mouseleave must have happend while the timer was running
                    if (!$this.data("hovering")) {
                        $this.removeClass('hover');
                    }
                }, 2000);
                // add marker to the object to show we have a timer running
                // so we won't clear the hover class while the timer is running
                // thus guarenteeing that the hover transition is allowed to fully complete
                $this.data("timer", timeout);
            }
        } else {
            // update "hovering" state
            $this.data("hovering", false);
            // if no timer running, then just remove the class now
            // if a timer is running, then the timer firing will clear the hover
            if (!$this.data("timer")) {
                $this.removeClass('hover');
            }
        }
    });
});