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

Unable to retrieve class object in PHP file loaded from AJAX request

I have encountered a minor issue with the following setup and I am seeking assistance to enhance my knowledge for future projects. Current Setup: There is a user class in PHP located within the models directory. A file named home.php is present in the r ...

the php renderer fails to take into account the styles

Trying to convey this as clearly as possible. I have the variables below: $name = main channel and $childs = sub channels. When I remove the childs from the HTML, only the main channel shows up - which is expected. However, when attempting to style the su ...

Using a hyperlink text instead of a button to make jQuery dialog functional

Although I managed to get it working, the issue is that it only works once. After the initial popup appears, the link stops functioning and the popup doesn't show up again unless I refresh the page. The code functions correctly within this JSFiddle ex ...

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...

Retrieving JSON information using jQuery

Is there a straightforward way to retrieve JSON data using jQuery? I have valid JSON that needs to be pulled efficiently. The JSON output looks like this: { "title": "blog entries", "items" : [ { "title": "Can Members of the D ...

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

The AJAX call returned undefined, leading to an error when trying to access the length property

I've scoured various resources to find a solution for this issue, but unfortunately, I haven't had any luck with implementing the code. The problem lies with my JSON parser function, which is designed to construct a table based on data received ...

Guide on removing a row from a mySql table with the help of AJAX

let tableName = "users"; let userID = 25; $("#btndel").click(function() { if (confirm("Are you sure you want to delete this item?")) { $.ajax({ url: 'ajaxdel.php', type: 'post', data: { ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

Does the layout.tsx file in Next JS only affect the home page, or does it impact all other pages as well?

UPDATE After some troubleshooting, I've come to realize that the issue with my solution in Next JS 13 lies in the structure of the app. Instead of using _app.tsx or _document.tsx, the recommended approach is to utilize the default layout.tsx. Althou ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

Enhancing the appearance of CSS Tables

I need help with applying a gradient line below each row of data that I am fetching from my database and displaying in a <table>. I've been able to achieve the design using an <hr> element, as shown here: http://jsfiddle.net/ghrw3k8e/. Ho ...

Switch from using jQuery to vanilla JavaScript for handling POST requests

I am looking to eliminate the jQuery dependency and use plain JavaScript instead in the code below for a post request. <script type="text/javascript> $(function() { $.post("test_post.php", { name: "John Doe", ...

The script is failing to execute in a modal dialog box

Can anyone help troubleshoot why this script isn't functioning properly in a modal window (PrettyPhoto)? I've attempted jQuery(document.body).ready(function(){ instead of $(function() { but I'm encountering the same issue: the script wor ...

Why isn't the jQuery colorbox popup appearing when triggered by the $.ajax() function?

I am currently facing an issue where I am trying to display a hidden colorbox popup using the $.ajax() method's success function, but it is not showing up. Interestingly, this had worked fine in a previous implementation where I used the data attribut ...

Add a product to your shopping cart in Opencart with the help of Ajax manually

My goal is to automatically add a product to the cart when a user clicks on a button using a custom function that I created. Here is the code for the button: <input type="button" value="Add to cart" onclick="addItemsToCart(83); " class="button btn-suc ...

Ways to retrieve text like innerText that functions across all web browsers

I need to retrieve the text from a Twitter Follow button, like on https://twitter.com/Google/followers Using document.getElementsByClassName("user-actions-follow-button js-follow-btn follow-button")[0].innerText correctly displays the text as: Follow ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

Seeking out all (including potentially relative) URLs on a webpage: Possible strategies to consider

For a coding challenge, I am working on a small python tool to download an entire website locally. In order to view the website offline, I need to convert all URLs to relative URLs. This is necessary to ensure that resource files (such as .js and .css) are ...

Is checking for an email address in a form necessary?

I am currently in the process of creating a coming soon page. I have included a form on the page where users can sign up using their email addresses, which are then sent to me via email. However, I need assistance in determining how to verify that the in ...