The JavaScript code will automatically execute loops

Let me illustrate my point with two functions.

Function 1
This function triggers a transition when you hover over the square. If you move your mouse off the element and then back on while the transition is still in progress, it will wait until the end of the function to repeat automatically. During this repetition, the object is non-interactive. For instance, if you hover over it while it's repeating, it will only toggle after completing the current cycle. Once finished, you can interact with the element again.

$(function () {
    $('square').hover(function () {
        $(this).addClass("makebig", 1000, "easeInBack");
    }, function(){
        $(this).removeClass("makebig", 1000, "easeInBack");
    });
});

Function 2
When you click on the square in this function, it triggers a transition by adding or removing a class. If you click on the square before the previous transition ends, the function waits for completion before toggling the class again. Clicking multiple times consecutively will result in multiple class toggles one after the other.

$("square").click(function() {
    $(this).toggleClass("big-blue", 1000, "easeOutSine");
});

The Question
Is there a way to make these functions interruptible?

In Function 1, can we stop hovering midway through to automatically remove the class? Similarly, in Function 2, can we interrupt the toggle transition by clicking again without waiting for the original transition to finish?

Edit
A user mentioned using the stop() function in jQuery to achieve interruption, but it has some limitations as seen in this JSFiddle. Any suggestions on improving the effectiveness of stop() would be helpful.

Answer №1

To successfully animate elements using jQuery, it's essential to consider the following two factors:

  1. Check if the element is still being animated when another event triggers
    This practice is commonly seen in jQuery animations triggered by events.
  2. Determine if the element is still being hovered (or no longer hovered) at the end of the animation, and adjust its state accordingly
    This is crucial for hovering animations or other scenarios where elements might get stuck in an incorrect state due to ongoing animations.

Neglecting these considerations can result in jQuery queuing up animations as you hover in and out of elements repeatedly.

You can view a working example here: https://jsfiddle.net/sf5q4jv0/10/

In my implementation, I have ensured that the "click" animation stops when a new one starts, while the "hover" animation must complete before another can be queued. By adhering to the two rules mentioned above, animating items to your desired effect should be straightforward.

$(function () {
     $('a[href*="#"]').click(function () {
         if($('html,body').data("anim")){
             $('html,body').stop();
         }
         $('html,body').data("anim", true);
         var $target = $(this.hash);
         $target = $target.length ? $target : $('html');
         var targetOffset = $target.offset().top;
         $('html,body').animate({scrollTop: targetOffset}, {duration: 1500, easing: 'easeInOutCubic'}, 
         function(){
             $('html,body').data("anim", false);
        });
        return false;
    });
});

/*Key section*/
$(function () {
    function hoverIn(element) {
      if(!$(element).data("anim")) {
        $(element).data("anim", true);
            $(element).addClass("hover", 1000, "easeOutBounce", function(){
            $(element).data("anim", false);
          //Remove class if element is no longer hovered
          if(!$(element).is(":hover")) {
            hoverOut(element);
          }
        });
      }
    }

    function hoverOut(element) {
      if(!$(element).data("anim")) {
        $(element).data("anim", true);
            $(element).removeClass("hover", 1000, "easeOutBounce", function(){
            $(element).data("anim", false);
          //Revert changes if element is still hovered
          if($(element).is(":hover")) {
            hoverIn(element);
          }
        });
      }
    }
    $('nav').hover(function(){hoverIn(this); }, function() {hoverOut(this); });
});

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

Tips on showcasing a collection of orders stored in a database using Vue.js

After successfully updating my orders post payment, I am wondering how I can showcase them on my Vue front end. Below is the HTML template displaying the list of orders made: <template> <div> <div v-for="order in orders&quo ...

What is the best way to ensure that the child element of a Material UI TableCell Component occupies the full height of the cell?

I am currently using MUI version 5 to create a table. In this table, there are two columns with cells that contain multiline TextFields. My goal is to have the TextFields completely fill the cell area. However, I am encountering an issue where when I start ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

Uploading files asynchronously with AJAX in Laravel

For the past couple of days, I've been attempting to make ajax file uploads work in Laravel 4, but unfortunately, I haven't had any success. This is my jQuery code: $(document).ready(function(){ $('#basicModuleImage').change(function ...

Unauthenticated user attempting to send a post request via React JS without proper authentication

Currently, I am working on a project where I am following a video tutorial that demonstrates how to authenticate a user using node and passport JS. The tutorial itself uses Hogan JS as its view engine, but I have decided to implement React as my front end ...

jQuery fails to make a POST request when the content type is set to application/json

I am utilizing jQuery version 1.10.1. My goal is to execute a POST request with the content type set to application/json. The code I have implemented is as follows: $.ajax({ type: "post", url: urlBase + "user/search", contentTy ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...

Limit the selection to just one element in a v-for loop in VueJS

I am utilizing Vue v2 My goal is to change only the properties of the selected element. Specifically, when the response is marked after clicking, it should switch to red color with a text that reads 'Unmark'. Conversely, if the button is clicked ...

Creating a horizontal scroll effect using jQuery when the widths of the items are not

I am working on a jQuery gallery that showcases images in a horizontal layout. Below the images, there are "left" and "right" buttons which allow users to scroll through the pictures. There are many tutorials and plugins available for this type of function ...

Is it possible to assign functions to each keystroke that does not correspond to a specific keybinding in Angular?

In Angular, there are events tied to keybindings or actions like (focus), (blur), (keydown), and more. You can bind specific keybinds to certain keys as well, such as (keydown.enter), (keydown.alt), etc. Is there a method to trigger an event only when it ...

IE7, IE6 display margins differently compared to other browsers

Can anyone help with an issue I'm having with a CSS ul list menu? #header-container #header ul.top-nav { float: left; margin: 20px 0 20px 10px; } #header-container #header ul.top-nav li { float: left; margin-right: 8px; border-rig ...

Display information from an array in a dynamic dropdown menu using jQuery-AJAX within the Laravel 4 framework

I'm currently facing some challenges while trying to create a dynamic select box using jQuery. The main issue lies in implementing a 'route' that accesses my database to retrieve data for the new select box: Route::get('contenidos/comb ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Could you explain the distinction among req.path, req.params, and req.query?

I'm curious about the distinctions among req.path, req.params, req.query, and req.body in node.js. Can someone provide an explanation? ...

The visibility of the Google +1 button is lost during the partial postback process in ASP.NET

When trying to implement the Google Plus One button using AddThis on one of our localized pages, we encountered a strange issue. Despite retrieving data from the backend (let's assume a database), the plus button was not loading during an AJAX based p ...

Issue with exporting data from Datatables

I followed the instructions, and the Datatables export function worked perfectly in localhost, but when I tried it in Google Apps script, it didn't work. For more information about the issue, you can visit this link: DataTables TableTools buttons not ...

Activate dynamic validation to ensure all necessary fields are completed before proceeding without the need to save

Is there a way to display the standard error message that appears next to required fields upon saving a form, without actually saving it? ...

I possess a high-quality image that I wish to resize while maintaining its resolution and clarity

I'm struggling with optimizing images for retina display on my website. I typically use the drawImage method, but I have a collection of large images (canvas drawn) that I want to use at half their size while maintaining image quality. Does anyone kn ...

Received undefined instead of a Promise or value from the function in Nodemailer

I'm currently exploring cloud functions and trying to implement email notifications for document creation triggers in Firestore. I found a helpful tutorial that guided me through the process, but I encountered an error while analyzing the cloud functi ...

What is the best way to upload multiple files using ASP.Net and Jquery?

On my aspx page, I have included the following JavaScripts... <script src="jquery-1.3.2.js" type="text/javascript"></script> <script src="jquery.MultiFile.js" type="text/javascript"></script> In addition, I have inserted the follo ...