Prevent clashes between mouseover and mouseleave events

I have been experimenting with this JavaScript fiddle found at http://jsfiddle.net/tPx6x/ The animation functions as follows:

When you hover over the text, a circle fades in and starts pulsating one second later. The pulsation continues for as long as your mouse remains over the text.

Once you move your mouse away from the text, the pulsation stops after a second and the circle fades out.

An issue arises when performing the following steps:

If you place your mouse over the text, then remove it quickly, and reposition it back over the text before the script finishes (within 1-1.4 seconds), the circle fails to appear properly again. You will need to wait for the script to reset, which presents a challenge.

How can we address this problem effectively?

Sample code snippet:

<div class='circle__title_project-management'>
 <h1>project management</h1>
 </div>
 <div class='circle__project-management hidden'></div>



.circle__project-management, .circle__title_project-management
{
    display: inline-block;
    cursor: pointer;
}

.circle__project-management
{   
    margin-left: 8px;
    vertical-align: -4.07px;
    background-color: transparent;
    border: 2px solid #00DBFF;
    width: 30px;
    height: 30px;
    border-radius: 90px;
    top: 280px;
    left: 40px;
}

.hidden
{
    visibility: hidden;
}

.visible
{
    visibility: visible;
}

.animate-infinite 
{
    animation-iteration-count: infinite;
    -moz-animation-iteration-count: infinite;
    -webkit-animation-iteration-count: infinite;
}



var circleTitle =  $('.circle__title_project-management h1');
var circle = $('.circle__project-management');
var initTimeout = 1000;
var initTimeoutPlus = 1400;
circleTitle.mouseover( function() {
    circle.removeClass('hidden');
    circle.addClass('animated fadeIn');   
    setTimeout( function() {
        circle.addClass('pulse animate-infinite');
        circle.removeClass('fadeIn');
    }, initTimeout);
});
circleTitle.mouseleave( function() {
    setTimeout( function() {
        circle.stop().removeClass('pulse animate-infinite visibility');
        circle.addClass('fadeOut');
    }, initTimeout);
    setTimeout( function() {
        circle.removeClass('fadeOut');
        circle.addClass('hidden');
    }, 1400);
});

Answer №1

It is important to remember that setTimeout has a return value. To avoid issues with timeout queues disrupting your animations, be sure to clear any previous timeouts before setting new ones. Here is an example:

var myTimeout;
...
clearTimeout(myTimeout);    
myTimeout = setTimeout(...);

This may not be exactly what you had in mind, but it follows a similar concept: http://jsfiddle.net/HGJ67/

For more information, check out:


Additionally, the circle.stop() function does not seem to have any effect since it is css-animated.

Answer №2

In order to prevent antagonist actions, consider assigning a specific class to your element when the event occurs and then removing it when a different event is triggered. By doing this, you will be able to effectively manage the situation.

Answer №3

To eliminate the time delay for mouseleave, consider setting a timeout for the mouseover function.

It's important to note that the initial run should not have any delays.

var initialTimeout = 1000;
var additionalTimeout = 1400;
var firstRun = true;
circleTitle.mouseover( function() {

    if (firstRun) {
        additionalTimeout = 0;
        firstRun = false;
    } else additionalTimeout = 1400; 

     setTimeout(function() {
         circle.removeClass('hidden');
        circle.addClass('animated fadeIn');   
        setTimeout( function() {
            circle.addClass('pulse animate-infinite');
            circle.removeClass('fadeIn');
        }, initialTimeout);
     }, additionalTimeout);
});

Answer №4

One way to achieve this is by setting a key on mouseover, toggling it after mouseleave, and checking the key before triggering any mouseleave timeout events. If the key is set, ignore the event; otherwise, proceed with executing mouseleave.

By using this method, if the key is "on," it indicates that a mouse over event occurred. If it is off, it signifies that the mouseleave event took place and is still ongoing.

    var flag = false;
circleTitle.mouseover( function() {
    flag = true;
    circle.removeClass('hidden');
    circle.addClass('animated fadeIn');   
    setTimeout( function() {
        circle.addClass('pulse animate-infinite');
        circle.removeClass('fadeIn');
    }, initTimeout);
});
circleTitle.mouseleave( function() {
    flag = false;
    setTimeout( function() {
        if (!flag){
            circle.stop().removeClass('pulse animate-infinite visibility');
            circle.addClass('fadeOut');
        }
    }, initTimeout);
    setTimeout( function() {
        if (!flag){
            circle.removeClass('fadeOut');
            circle.addClass('hidden');
        }
    }, 1400);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I cut an array by value in Vue?

I am working on a component that has a list of objects and I need to implement functionality where, when toggled, the objects' title prop is either added to or removed from an array. Adding the value was easy to do, but removing it has proven challeng ...

Retrieve a zip file using React and Node from a RESTful API

I have an application built with React and Node where I have a table that includes a download button. Clicking the download button triggers a request to my Node app, which in turn should call a REST API to download a zip file directly into the browser. In ...

Working with PHP and CodeIgniter to highlight active nav-link in Bootstrap for a subdirectory

Just starting out with Bootstrap and running into a little issue. Spent some time on it but can't seem to figure it out. Perhaps it's something simple that I'm overlooking. Essentially, my goal is to keep the nav-link active when navigating ...

What signals to Angular that $httpBackend is substituting $http during the testing of AngularJS?

My factory, called myFactory, has a dependency on $http. When writing tests for this, I needed to mock this dependency. After some research, I discovered that I could accomplish this using $httpBackend. Implementing the code below successfully achieved t ...

Struggling to locate desired href links using BeautifulSoup

I'm currently working on compiling a list of hrefs from the Netflix job portal: . Each job posting on this platform comes with an anchor and a specific class: <a class=css-2y5mtm essqqm81>. To ensure accuracy, here is the complete anchor: <a ...

Ways to eliminate line breaks in a specific script

I am brand new to using phonegap and I need some help figuring things out. Here is the script source: <script src="http://www.transfermate.com/en/exchange_rates_api.asp"></script> I am attempting to remove the s in the div 'currency_c ...

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

Leverage the power of jQuery to display JSON data retrieved from a PHP

I am having trouble with my jQuery AJAX call on a PHP page that outputs JSON. Despite my code seeming correct, the alert() dialog isn't showing and the JavaScript console isn't providing any errors. Can you help me identify what is causing this i ...

Struggling to integrate Ajax with Angular framework

Looking to learn Angular. Attempting to integrate Angular with AJAX calls. Whenever I try to access http://localhost:9091/jerseyservlet/jerseyrest/org/orgId/DEY using a browser or any REST client, the following response is displayed: <users> & ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

Adding data from a user-input table into a mySQL database

I'm currently working on a dynamic table form input form that allows users to add/remove rows as needed. However, I am facing a challenge in saving these inputs into mySQL database due to my lack of experience. Below is the structure of my input.php: ...

Align the content to the center of the middle column using HTML

Is it possible to replicate Amazon's email structure using only HTML in the feedbackwhiz template editor? I want my content to be left-justified in the center column with white space on either side, similar to the Amazon email example provided. Amazo ...

Display of content visible via stationary div

Recently, I successfully implemented a fixed div that remains at the top of my webpage. However, I encountered an issue where text would appear through the div when scrolling. You can witness this phenomenon by visiting this site and simply scrolling down ...

Updating the URL in React and Redux

I am currently working on developing an application using React and Redux (DVA) with Ant.Design as the main framework. I am facing an issue where I need to change the URL when a user clicks on a button, and connect that URL change to a specific action so t ...

CSS: The search field's results are displayed in a width that is half of

There seems to be an issue with the search dropdown results on my website. When you click on the magnifying glass in the top menu and try to search, the results only appear as half the width of the search form. I would like to know how I can display it i ...

What is the secret behind Vuetify's ability to offer components without the need for imports in Vue?

Within the vuetify framework, various components such as sliders are actually accessible without requiring explicit imports. I wonder how vuetify manages to achieve this special functionality? ...

The index falls outside the acceptable range

I've encountered a problem with the Tone.Analyzer in Safari 10.1. When setting the Tone.Analyzer with a size > Math.pow(2, 10) (1024), I'm faced with the following error: IndexSizeError (DOM Exception 1): The index is not in the allowed range. ...

java script loop - how to save index values

Planning to create a program that extracts the domain from an email address. How can this be done without using built-in functions like .map .filter .reduce .split .join .indexOf .findIndex .substring? Many online sources suggest using a for loop to locat ...

Tracking the status of lengthy processes in MVC 5

Preface: I have referenced a helpful article for my project. You can find it here. I am working on providing visual feedback to the user when they submit a form. I was inspired by YouTube's progress bar and wanted to implement something similar wher ...