Stopping a jQuery function from executing multiple times while it is already active - is it possible?

Currently, I am utilizing the http://jsfiddle.net/CqAU2/ plugin for image rotation on my website. The issue I am facing is that when the user clicks on the image box multiple times, it continues rotating each time. I want the click action to only be registered when the box is stationary. Is there a way to achieve this?

Answer №1

To prevent the action from being triggered while still animating, you can use a flag that acts as a 'lock'. This flag can then be reset after the same duration as your animation (in this case, 1000ms):

$(document).ready(function () {
    var degree = 0;
    var locked = false;
    $(".big-ball").click(function () {
        if (!locked) {
            degree += 30;
            $(this).jqrotate(degree, 1000);
            locked = true;
            setTimeout(function(){
                locked = false;
            },1000);
        }
    });
});

Check out the updated Fiddle here

Answer №2

Did you achieve the desired outcome?

http://jsfiddle.net/wq6pp/

Prior to initiating the animation, I included the stop() method.

$(elem).stop().animate({...})

What is the purpose of the stop() method?

When .stop() is utilized on an element, it promptly halts any animation that is currently in progress.

For further information on stop(), visit: http://api.jquery.com/stop/

Answer №3

Here is an updated version of your code with a control in place to prevent multiple clicks:

$.fn.jqrotate = function (degrees, speed) {
    if(typeof $.preventTwo !== "undefined" && $.preventTwo == false) return;
    $.preventTwo = false;
    return this.each(function () {
    var elem = this;
    elem.x = $(elem).data('rot')||0;

    $(elem).animate({
        x: degrees
    }, {
      duration : speed,
      step: function( now, fx ) {
        $(fx.elem).css({
              '-webkit-transform' : 'rotate('+now+'deg)',
                 '-moz-transform' : 'rotate('+now+'deg)',
                  '-ms-transform' : 'rotate('+now+'deg)',
                   '-o-transform' : 'rotate('+now+'deg)',
                      'transform' : 'rotate('+now+'deg)'
         }).data('rot', now);
      },
      complete : function(){
          $.preventTwo = true;
      }
    });

});
};

$(document).ready(function () {
    var degree = 0;
    $(".big-ball").click(function () {
        degree += 30;
        $(this).jqrotate(degree, 2000);
    });
});

Goodbye for now... http://jsfiddle.net/CqAU2/1/

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

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

JavaScript visibility disappearing intermittently

I have created a custom image viewer box that overlays a thumbnail gallery page. The image viewer should appear when a user clicks on a thumbnail. However, currently, the viewer only pops up briefly and then disappears again. I am looking for a way to mak ...

Can I kindly request assistance with implementing jQuery Autocomplete on a C# IHttpHandler in a non-sequential

Currently, I have an autocomplete textbox that is requesting an IHttphandler through IIS7 using C#. However, it seems like the requests reaching the web server are arriving unordered. Below is a snippet of the log obtained from the IHttpHandler after typ ...

Error: EPERM -4048 - the system is unable to perform the operation specified

Every time I attempt to install a package using npm install, I encounter an error message (usually referring to a different path). I have attempted running npm cache clean, restarting my computer, and checking for any processes that may be interfering with ...

Unable to submit a fetch request

I've been searching for quite some time without finding any answers to this particular issue. The problem I'm facing is that when I attempt to send an asynchronous request to another web page, I'm not receiving any response. I suspect that t ...

Fuzzy background when you scroll

My container has an image that blurs when you scroll down the page by 50 pixels. I feel like I've seen this effect somewhere before, but I can't quite recall where. I want the text to remain unaffected and not turn blue. Here is the HTML: <d ...

Unusual patterns appearing in HTML image files

As a beginner in html, please pardon my silly questions and mistakes. I have designed this webpage: <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <style type = text/css> #topbar { ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

flask - Transfer data from Python to HTML using a database

I have written code to fetch data from a database and now I want to display it in an HTML format. Below is the code snippet from app.py @app.route('/news') def news(): import pymysql import re host='localhost' user = ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

Retrieve the value of data from a JSON object

I am looking to extract the ID data only {"register":{"id":"1","members_count":null,"name":"Neha","user_name":"Neha","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7119141d015f14150414090103140202181e1f5f121e1c31161c ...

Show or conceal a child component within a React application

In my React render function, I am working with the following code: <div> <InnerBox> <div>Box 1</div> <HiddenBox /> </InnerBox> <InnerBox> <div>Box 2</div> & ...

Extracting data from Material-UI TextField elements in React – a guide

I am currently working on a small app that consists of a Form component, a SubmitButton component, and my parent component, App.js. My goal is to retrieve the values of the 3 fields within the form component when the user clicks the submit button, pass the ...

The unexpected syntax error, indicated by an ampersand followed by a quotation mark, was encountered in [location] on line 7

Every time I try to run my code, I encounter the following error message: Parse error: syntax error, unexpected '"' in D:\server\WT-NMP\WWW\myproj1\insert.php on line 7 This is the code that is triggering the error: &l ...

Add HTML content to a specific div according to the option selected in a drop-down menu

I am currently working on a project where I need a button to insert HTML content into a div based on the value selected in a select box. However, the functionality is not working as intended. Upon clicking the button, nothing happens. I am unsure of what t ...

Stylish dots emerging under navigation bar

Okay, so I've run into a simple issue, but I can't seem to figure out the solution. Ever since I wrote this code, I've noticed these small dots appearing below the menu. Take a look at the image for a clearer picture. https://i.sstatic.ne ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

Utilize the split functionality only when the character you want to split by is found in

Consider the following situation: I have 6 string variables that contain special characters. I stored these 6 strings in an array like this: arr=[str1,str2,str3...); arr=escape(arr); due to the presence of special characters in some string variables. ...