What methods can be used to add a delay to a toggleClass event in order to prevent rapid

After implementing the jQueryUI toggleClass delay function, I noticed that it introduces a delay before the event occurs instead of setting a specific timing for when it can be triggered again.

I have multiple DIVs that switch classes when hovered over using the toggleClass method. However, if the cursor moves rapidly over them, they keep switching and create a glitchy effect. I want to prevent this by potentially limiting the toggle to occur only once every second or some other specified interval.

Is there a way to achieve this?

    $(".landingImage").hover(function () {
            var curHeight = this.clientHeight;
            $(this).siblings('.imageCover').css("height", curHeight / 1.25);
            $(".leftLanding").toggleClass("extraMargin");
            $(".rightLanding").toggleClass("extraMargin");
            $(this).siblings(".imageCenter").fadeOut(50);
        }, function () {
            $(this).siblings('.imageCover').css("height", "0px");
            $(this).siblings(".imageCenter").fadeIn(600);
    });
    #landing-images {
        position: relative;
        width: 100%;
        height: auto;
        overflow: auto;
        margin-top: 6%;
        margin-bottom: 5%;
    }
    
    .leftLanding {
        display: flex;
        position: relative;
        width: 85%;
        margin-left: 3%;
        cursor: pointer;
        transition: all 0.5s ease;
    }
    
    .rightLanding {
        display: flex;
        position: relative;
        width: 85%;
        margin-right: 3%;
        cursor: pointer;
        transition: all 0.5s ease;
    }
    
    .extraMargin {
        margin-left: 12%;
        margin-right: 12%;
    }
    
    .landingImage {
        position: relative;
        display: block;
        width: 100%;
        height: auto;
        z-index: 90;
        transition: all 0.5s ease;
    }

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="landing-images">
        <a href="menu.html"><div class="leftLanding left">
            <div class="imageCover">
            </div>
            <div class="imageCenter">
                
            </div>
            <img class="landingImage" src="assets/landingIMG1.png">
        </div></a>
        <a href="contact.html"><div class="rightLanding right">
            <div class="imageCover">
            </div>
            <div class="imageCenter">
               
            </div>
            <img class="landingImage" src="assets/landingIMG3.png">
        </div></a>
        <a href="burritos.html"><div class="leftLanding left">
            <div class="imageCover">
            </div>
            <div class="imageCenter">
           
            </div>
            <img class="landingImage" src="assets/landingIMG2.png">
        </div></a>
    </div>

Answer №1

To conditionally postpone the hover event, you can delay it by using window.setTimeout.

The concept is to - set a short delay before triggering the change - handle the mouse out action to prevent the pending change.

This snippet of code demonstrates how to achieve that:

var delay;
$(".landingImage").hover(function () {
    window.setTimeout(doit,250);    //   queue action
}, function () {
    cancel();   //  clear hover, if still pending
    $(this).siblings('.imageCover').css("height", "0px");
    $(this).siblings(".imageCenter").fadeIn(600);
});

function doit() {
    var $landingImage=$(".landingImage");
    var curHeight = $landingImage.clientHeight;
    $landingImage.siblings('.imageCover').css("height", curHeight / 1.25);
    $(".leftLanding").toggleClass("extraMargin");
    $(".rightLanding").toggleClass("extraMargin");
    $landingImage.siblings(".imageCenter").fadeOut(50);

    delay=undefined;
}
function cancel() {
    if(delay) delay=window.clearTimeout(delay);
}

Since setTimeout is a method of window, this no longer references the original element. In this code, I have assigned the original element to a variable. I usually prefix jQuery variables with $, but that's just personal preference.

I haven't tested this in your specific environment.

If you prefer a CSS approach:

To avoid abrupt changes and introduce a slight delay, you can include the following line in your CSS:

transition-delay: .25s;

You can also combine transition-delay with the general transition property (placing it last), but it's recommended to try this configuration first to observe its effects.

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

What's with the increased verbosity of mongoose query result objects in the latest version?

After installing my dependencies on a new computer, I noticed that mongoose must have been updated. The informative results from my queries are now appearing in messy outputs with excessive information that is not always useful. It used to be concise and c ...

JavaScript code in AJAX response functions properly in browsers like Firefox, Chrome, and Opera. However, it encounters issues in Internet Explorer 11, displaying an error message stating

After searching through various posts, I was unable to find a solution to my question. My query involves requesting a jQuery Datepicker via AJAX. I have provided an example for you to review in Firefox, Chrome or Opera: Ajax javascript example Unfortuna ...

The $_POST request was interrupted and data was severed

I am currently facing an issue with my $_POST request. I am sending an array with 855 records through AJAX, but my AJAX controller is only receiving 833. The strange part is that it consistently cuts out at the same point: Here is my JQuery code: var for ...

A POST request to Ajax results in a bad request error code (400)

I am looking for assistance with an ajax call that is not working as expected. I'm having trouble understanding why this is happening. Could someone please review my code and provide some insight? It appears that the call is not reaching the control ...

Ajax- priorToSend

To avoid encountering the same error twice, I implemented the use of beforeSend in my code. hasSent = false function submit() { if (!hasSent) { $.ajax({ url: "${createLink(controller:'userInvitation', action:'ajaxUp ...

Unable to display favicon when using the include function

How can I add the favicon link to my website? In my header.php, I have added the link for my ico favicon, but when I try to include it in my index file, the favicon does not show up. I attempted to insert the favicon code directly into the index.php file, ...

What could be causing the error message 'Why is 'push' property undefined in React Native?

Within my index.ios.js file, I have the following: renderScene(route, navigator){ return <route.component navigator={navigator} {...route.passProps}/> } as well as render() { return ( <Navigator initialRoute={{name: &a ...

Can a JavaScript function be sent through a REST API using Node.js and Express?

I have a unique scenario where I need to send a custom JavaScript function as a response to a GET request made to an API endpoint. Currently, I am using Node.js with Express for my server implementation, but I am open to exploring other frameworks. When a ...

Leveraging UseRouter.query Data in Next.js Content Display

I'm currently diving into routing in Next.js and running into an issue where the query values are not being included in the HTML response. Despite recognizing that isReady is false and the return is happening before the variables are set, I'm uns ...

Animating transitions when hovering (using jQuery)

As a newbie to jQuery, I am currently exploring how to create an animated transition for a headline. I stumbled upon this CodePen (http://codepen.io/ansac/pen/BHtkE) but it doesn't quite match what I have in mind. My main query is: How can I maintain ...

Vuetify vueJS dialog with elevated design

Is there a way to completely remove the elevation of a v-dialog so that it has no shadow at all? The elevation property in the v-dialog itself and using the class as Class = "elevation-0" have not worked for me. Here is the link to the component ...

The AudioPlayer refuses to play following a track change

I am looking to implement an audio player in React Nextjs that features interactive dots, each representing an audio track. The functionality I want is such that clicking on a dot will pause the currently playing track (if any) and start playing the select ...

Is the percentage width and height for setting the size of an image in html/css mobile based on the screen's dimensions?

Currently, I'm working on an Oracle Apex jmobile query project involving an HTML page that includes the following image code: <center> <img src="#WORKSPACE_IMAGES#Logo.svg" align="center"> </center> Additionally, there is CSS to st ...

Add a specific identifier to an HTML element

Struggling to add a class or id to an HTML element for styling. Here's the code snippet: $('<li/>').append($('<p>', {html: val.title}), $('<p>', {html: 'Posted on ' + split[0]}) Tried the fol ...

Transforming an Ionic mobile application into a web-based application: A step-by

I currently have a mobile app developed using Ionic. I now require a desktop-friendly website version of the app to cater to users who wish to access it from their computers. Can anyone point me to any resources or documentation that demonstrate that th ...

Combining iDangerous Swiper with jquery .click() for Ultimate User Interaction

Need some help with this issue: I'm currently utilizing the iDangerous Swiper plugin, which is functioning properly. However, I also want to implement jQuery's click function on that same iDangerous swiper. For instance: <div id="swiper-con ...

How come the dark grey in CSS appears to be lighter than the standard grey hue?

JSBIN DEMO Could this be a mistake or is it a bug? Shouldn't the dark gray shade be darker than the default grey one? HTML <div class="lightgrey">Light Grey</div> <div class="grey">Grey</div> <div class="darkgrey">Dar ...

Switching from a curl command to the jQuery $.ajax() method

Struggling to make an api call using jQuery ajax. I have successfully set up a curl command for the API, but my ajax request keeps throwing HTTP 500. This is the working curl command I have: curl -u "username:password" -H "Content-Type: application/json" ...

Tips for implementing a hover transition effect in the navigation menu

I have a specific query regarding a particular issue that I am unsure how to address but would like to implement on my website. 1) My requirement is that when the parent li element has a child, I want the navigation to remain in a hovered state with the s ...

Ways to display JSON result array without using JavaScript code

I am working on a script that consults an external API to retrieve specific data. My goal is to display only the array result without any visible JS or HTML code. I believe this is achievable, but unfortunately, I am unsure of how to implement it. As some ...