Prevent clicking on the <div> element for a duration of 200 milliseconds

I need to make this box move up and down, but prevent users from clicking it rapidly multiple times to watch it go up and down too quickly. How can I add a 200 millisecond delay on the click or disable clicking for that duration?

View the jsfiddle example here: http://jsfiddle.net/QwwUD/4/

 <html>

<style>
div {
position:absolute;
background-color:#abc;
left:50px;
width:90px;
height:90px;
top:100px;
margin:5px;
}
</style>

<div class="block" id='up' disabled='true'></div>

<script>

$('.block').click(function(){


    if($('.block').attr('id') == 'up'){
        $('.block').animate({'top': '-=50px'}, 200);
        $('.block').attr('id', 'down');
    } else{
        $('.block').animate({'top': '+=50px'}, 200);
        $('.block').attr('id', 'up');
    }
});
</script>
</body>
</html>

Answer №1

Give this jQuery animation tip a try:

http://jsfiddle.net/QwwUD/1/

You can use the .stop method in your animation to control its behavior. Here is an example using it within a click function:

$('.block').click(function() {

    var btn = $('.block');
    btn.prop('disabled', true);
    window.setTimeout(function() {
        btn.prop('disabled', false);
    }, 600);

    if ($('.block').attr('id') == 'up') {
        $('.block').stop(true,true).animate({
            'top': '-=50px'
        }, 200);
        $('.block').attr('id', 'down');
    } else {
        $('.block').stop(true,true).animate({
            'top': '+=50px'
        }, 200);
        $('.block').attr('id', 'up');
    }
});​

Answer №2

To prevent the click event while it's animating, you can utilize the following code:

$('.block').click(function(){
    if ( $(this).is(":animated") ) return false;
    ... continue with your code ...
});

Personally, I opt for stopping the animation as recommended by Esailija.

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

Differentiating between mouseenter and tap events: What's the key?

When a mouseenter event is present, touch-enabled devices will activate this event when the user taps on the element. Is there a way to differentiate between an actual physical mouse entering and a simulated tap (which resembles a mouse enter)? ...

What is the best way to conceal the initial column using jquery?

Is there a way to automatically hide the first column of data as it loads from a csv file using jquery and AJAX? I know you can do this using onclick function, but I prefer to have it automatically hidden. How can I achieve this? Below is the sample CSV d ...

Choose the list item by identifying the corresponding unordered list

Is there a way to target the second li element within an ul list like this: HTML <ul> <li></li> <ul> <li>This one is what I need to select</li> </ul> </ul> ...

Passport.js does not provide authentication for server-side asynchronous requests

Recently, I configured Passport.js with the local-strategy on my express server. Interestingly, when I am logged in and send an asynchronous request within NextJS's getInitialProps, it allows the GET request through client-side rendering but not serv ...

Tips for handling data strings using axios

In my node.js project, I am following a manual and attempting to display data obtained from jsonplaceholder app.get('/posts', async (req, res) => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Creating a zebra-striped list using CSS can be done by styling even and odd list items differently

I am facing an issue with Angularjs and the table tag when using group loops. The problem arises in achieving correct zebra striping for the list. How can I solve this to ensure the zebra pattern is applied correctly? <table> <tbody> <tr ...

React Select streamlines dropdown options for multi-selection by abbreviating names

Is there a way to shorten dropdown names when selected similar to the example shown in the image below This is the snippet of my code : multiValue: [ { value: "BUF", label: "BUF" }, { value: "CCT& ...

I am unable to select the first item when using select2.js and setting a placeholder

I am experiencing an issue with my <select> list that is styled using select2.js. Everything seems to be functioning properly, except for when a placeholder is used. Users are unable to select the first item in the list initially. If they choose any ...

Tips for organizing your JSON Structure within ReactJs

In the given example, I have a JSON structure with information about different airlines. The Airline Name is dynamic and we need to separate the JSON into an expected array format. const arr = [ { Airline: "Goair", Departure: "01:50" ...

Emerald: Fresh alert for numerous attributes

After updating jade to the latest version, I started seeing a message in the console that says: You should not have jade tags with multiple attributes This change was mentioned as a feature here 0.33.0 / 2013-07-12 Hugely more powerful error reporting ...

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

Express js is not returning a value from a recursive function?

I've been working on an ecommerce website where I created a mongoose model for all categories. However, the challenge arises when dealing with subcategories that require a parent id in the database. When a request is made, all categories are retrieved ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

Steps to obtain an Element binding from a Svelte component

Is it possible to retrieve the bounding client rect of an anchor element? I typically mark this using the syntax bind:this={someVariable}. However, when I add this code to a Svelte component, I receive a different object that Svelte uses to represent a c ...

most effective approach for recurring AJAX requests

Currently working on a web app that includes real-time features such as chat and auto-updating lists. Looking for the best method to perform interval updates using AJAX. My current approach is quite simple: updateAll(); function updateAll(){ $.ajax({ ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...