I successfully created an animation with jQuery for an image, but unfortunately, it seems to malfunction during the second

$( "#btn1" ).click(function() {

   var $this = $(this);
   var clickCount = ($this.data("click-count") || 0) + 1;
   $this.data("click-count", clickCount);

    if (clickCount%2 == 0) {
        $("#img1").hide('clip').animate({
            marginLeft: "40%"

        },1500);
    } else {
        $("#img1").show('clip').animate({
            marginLeft: "40%"
        },1500);
    }

});

Issue arises when the jQuery animation behaves differently after hiding and then showing the image for the third time. The animation speed is faster and does not work properly.

Check out a working example here

Answer №1

Check out the Demo

There's a speed issue that arises when clicking the button before the animation is complete. To avoid this problem, you can disable the button when it's clicked and then enable it again after the animation finishes. Additionally, it's recommended to reset the style after each animation completes. Take a look at the code snippet below for implementation.

$("#btn1").click(function() {
var button = $(this);
button.attr("disabled", true);
var $this = $(this);
var clickCount = ($this.data("click-count") || 0) + 1;
$this.data("click-count", clickCount);

if (clickCount % 2 == 0) {
    $("#img1").hide('clip').animate({
        marginLeft: "40%"

    }, 1500).promise().then(function() {
        button.removeAttr("disabled");
    });
} else {
    $("#img1").removeAttr('style');
    $("#img1").show('clip').animate({
        marginLeft: "40%"

    }, 1500).promise().then(function() {
        button.removeAttr("disabled")
    });
}

});

Answer №2

Check out this cool demo on http://jsfiddle.net/GaganJaura/y5devv2j/2/. It's fully functional!

$( "#btn1" ).click(function() {

   var $button = $(this);
   var clickCounter = ($button.data("click-count") || 0) + 1;
   $button.data("click-count", clickCounter);

    if (clickCounter % 2 == 0) {
       $("#img1").hide('clip').animate({
    marginLeft: "0px"

    },1500);
    }
    else
    {
        $("#img1").show('clip').animate({
    marginLeft: "200px"

    },1500);
    }

});

Answer №3

Check out this link

if (clickCount%2 == 0) {
       $("#img1").hide('clip').animate({
    marginLeft: "0%"
    });
    }
    else
    {
        $("#img1").show('clip').animate({
    marginLeft: "40%"
    });

Answer №4

Check out your jsFiddle Demo. The animation seems a bit too fast, consider increasing the duration for a smoother effect.

if (clickCount%2 == 0) {
   $("#img1").hide('clip').animate({
marginLeft: "0px"

},3000);
}
else
{
    $("#img1").show('clip').animate({
marginLeft: "40%"

},3000);
}

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

Stop JQuery Timepicker from showing by using beforeShow event

I've been trying to figure out a solution for this issue, but so far I haven't been successful. When using the timepicker, there is a beforeShow property that I want to utilize for validation purposes. I need the timepicker to only appear if the ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

Error: Data type exception encountered in JSP file

Currently, I am developing a web application that involves generating a table dynamically using Ajax. The data for this table is retrieved from the database. Below, you can find the code snippets related to this functionality. Index.jsp <html> <h ...

The functionality of jQuery click events seems to be disabled on the webpage, however, it is working perfectly fine on jsFiddle

After thoroughly checking the js tags and ensuring everything is properly closed, it's frustrating when the JavaScript suddenly stops working. The code functions perfectly in JSFiddle, leading me to believe that the issue may lie with something I&apos ...

The sidebar in Semantic UI does not have a specified height for the form segment

Need help troubleshooting a button that slides out a vertical sidebar. I want to include a short form for users to input search queries within the sidebar. The issue seems to be with the heights of #search-sidebar and .ui.form.segment. Here is the code s ...

Save the input from an HTML text area tag as a Word or PDF file using C# code

In the midst of a challenging ASP .NET project, there is a need to download the content of a text area as a file in formats like .doc, .pdf, and .txt. While it's common knowledge that plain text can be downloaded as .txt using JavaScript, the real qu ...

Ways to embed an HTML file into another HTML document

I have been attempting to include a footer.htm file in my index.htm document without success. Below is the code I am using. index.htm <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.d ...

The act of determining the position and dimensions triggers the CSS transition

Okay, here's an interesting scenario: When you add an element to the DOM using jQuery and then immediately apply addClass, you may notice that there is no CSS transition. Surprisingly, if you perform any calculation method like position(), offset(), ...

Another ajax function implemented for a different form is experiencing technical issues

I have two forms with different IDs (form_sign and form_login) and I am using AJAX to submit them. The form_sign is working fine, but the other form is not functioning properly. When I tried to display an alert after submitting the form_login function, it ...

Learn how to utilize the getElementByClassName method in JavaScript to insert checkboxes into two lists that share the same class name

I have a situation where I have two lists sharing the same class name. I need to dynamically create checkboxes in both of these lists based on XML data. My current dilemma lies in how to properly utilize getElementByClassName in JavaScript to add checkbox ...

A Bootstrap navigation sidebar with a secure footer and a div that can be scrolled

In the image below, you can see that the scrollable TreeView in the sidebar is not functioning properly. Additionally, I need to have a fixed footer for this sidebar that remains in place when users scroll through the content. How can I resolve this? http ...

Using PHP to send a JSON request via cURL

I am attempting to make a cURL request in PHP. The request I am trying to send is as follows: $ curl -H 'Content-Type: application/json' -d '{"username":"a", "password":"b","msisdn":"447000000001","webhook":"http://example.com/"}' http ...

Can you explain the owlItem feature found in owl carousel?

Does anyone have an idea about this? .data("owlItem") How can I find this in jQuery or the console log? I don't think this is a data attribute. .data("owlItem") .data("owlItem") $("#slider_thumb").on("click", ".owl-item", function(e){ ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

How can I ensure that my content stays fixed at the bottom of a scrolling div in Material UI React?

I have developed a React JS component using Material UI that includes a chat input feature. However, I am facing an issue where the width of the chat input is always half the screen size on desktop or mobile devices. When I try to change the width to 100%, ...

Discovering the information lined up in a single row

The row consists of: Row Number -- Name Surname -- Instructor Name -- Grade </tr> <tr height=20 style='height:15.0pt'> <td height=20 class=xl6429100 align=right width=28 style='height:15.0pt; border-top:none;width:21pt&apo ...

Divide the data using commas (,) for separation and showcase it in the appropriate manner

When an error occurs, my Controller will return the following: return "0".",".$messages = $validator->messages(); This will result in the following output: 0,{"firstname":["The firstname field is required."]"lastname":["The lastname field is required ...

Creating a unique store previewer customization

Are there any JavaScript libraries available to simulate the CSS image-mask property since it is not widely supported by browsers? I've been experimenting with creating a white image containing transparent areas in the shape of the design elements I w ...

How can I display a button (hyperlink) on a new line using CSS or jQuery?

I am looking to create a new line after the last input of my form. On this new line, I want to add a "remove-link". This is my HTML: <div class="subform dynamic-form"> <label for="id_delivery_set-0-price"> Price: </label> <inp ...

Issues with Wamp server's CSS display are frustrating and need to

I have created a pair of divs in a .css file and then I connected that .css file in a php header file as shown below: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/headercss.css" type="text/css" media="screen" title ...