The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with:

$(document).ready(function(){

    $(".subscriptions").click(function (){

        if($(".pollSlider").css("margin-right") == "-200px"){
            $('.pollSlider').animate({"margin-right": '+=200'});
            }else{
            $('.pollSlider').animate({"margin-right": '-=200'});
            }
        });

//other exceptions

if($(".pollSlider").css("margin-right") > "200px"){
    $(".pollSlider").css({'margin-righ':'200px'});
    }
if($(".pollSlider").css("margin-right") < "0px"){
    $(".pollSlider").css({'margin-righ':'0px'});
    }
 }); 

This CSS determines the styling of the element in question:

.pollSlider{
    overflow: auto;
    top:0px;
    position:fixed;
    height:100%;
    background:red;
    width:200px;
    right:0px;
    margin-right: -200px;
    z-index:100;
}

I have a div that slides in and out when a button is clicked. It slides 200px to the left on the first click, and then 200px to the right on subsequent clicks. The issue arises when multiple clicks are made while the animation is still in progress, causing the div to slide off-screen and not return. I attempted to add some conditions to prevent this but they did not work as expected. How can I resolve this problem?

Answer №1

In my demonstration, I have attempted to replicate the desired effect you are aiming for. The use of jQuery's .stop(…) function is crucial in ensuring that the animation queue is cleared before initiating the subsequent animation.

I made a change by switching from relative units (+=200 and -=200) to fixed values (0 and -width). This adjustment is necessary in case the animation halts midway and there is a requirement to animate back. By opting for fixed values, or performing real-time calculations before each new animation, this issue can be effectively addressed.

Answer №2

One strategy I use to tackle this problem is by implementing a global variable that controls the animation process. The variable is initially set to false after a user click and then switched back to true once the animation completes:

var allowAnimate = true;
$(document).ready(function(){

$(".subscriptions").click(function (){
    if(allowAnimate){
        if($(".pollSlider").css("margin-right") <= "-200px"){
            allowAnimate = false;
            $('.pollSlider').animate({"margin-right": '+=200'}, function(){allowAnimate = true});
        } else if($(".pollSlider").css("margin-right") >= "200px")){
            $('.pollSlider').animate({"margin-right": '-=200'}, function(){allowAnimate = true});
        }
    }
});

//other exceptions
....

When a user clicks a button, the allowAnimate variable is checked for its value. If it is true, I set it to false to initiate the animation. Once the animation finishes and the callback function is triggered, the variable is set back to true.

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

Chrome now supports clickable circular canvas corners

I have a unique setup with two canvases. I've customized them to be circular by utilizing the border-radius property. The second canvas is positioned perfectly within the boundaries of the first one using absolute positioning. This is where it gets e ...

Execute various functions with toggleClass() upon clicking using jQuery

I am looking to execute multiple actions at the same time when a button is clicked. In my JavaScript code, I am using toggleClass() function in jQuery to toggle the visibility of a burger icon. Toggling the menu on click is working as expected. However, I ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...

Display a comprehensive inventory of all bot commands within a designated category

When a user executes a command, I have various commands categorized and would like to present them accordingly. For instance, consider the following command: const Discord = require('discord.js') const { MessageEmbed } = require('discord.js& ...

The initial item in the Materializecss slider is failing to display

Currently, I am attempting to implement materialize slider with skrollr. The setup is functional; however, only the first item of the slider is set to opacity: 0 initially. https://i.stack.imgur.com/urSww.jpg After a brief delay, the second item becomes ...

What is the best way to reset an a-select component in Ant Design Vue?

I need to programmatically reset the selection in my a-select component after a specific event is triggered. Here's an example of my a-select code snippet: <a-select style="marginTop: 8px;width: 20%" @change="onChanged" > ...

URLs not being gathered by the web scraping tool

Currently involved in scraping data from this specific website to compile a database. Previously, I had functioning Python code available on GitHub that successfully accomplished this task. However, due to a major overhaul in the HTML structure of the site ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

Past methods: Obsolescence alert and caution

Trying to grasp the concepts of PHP & MYSQL, I have written this code which seems to be functioning properly. However, there are several "warnings" that I am unsure about. Nonetheless, PHP successfully connects to the database. Below are the relevant codes ...

Something is wrong with the OMDb API search using JQuery and JSON

I am currently experimenting with APIs to enhance my website. One of my projects involves using the OMDb API to search for a movie title and display its poster on my site. However, I seem to be encountering some difficulties with the code implementation. ...

Creating a simple bootstrap code for developing plugins in Wordpress

After successfully coding in Brackets with the Theseus plugin on my local machine, I encountered a problem when attempting to transfer my code to a Wordpress installation. The transition from Brackets to Wordpress seems far more complicated than expected. ...

A guide on designing a personalized search bar for MUI-Datatables with a sleek outlined style

Check out the default UI from MUI-Datatables v4.3.0 here: https://i.stack.imgur.com/rbHgD.png I want to create a style similar to this: https://i.stack.imgur.com/AUHqC.png Just so you know, I am using the following packages: "@mui/material": &q ...

Next.js triggers the onClick event before routing to the href link

Scenario In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables. Objective I aim to trigger the onClick function before navigating to the href location. The Code I'm Using <Link href={`/sess ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

Tips for Positioning a Page Layout in the Center Using HTML and CSS

I'm a beginner in HTML and CSS and I'm trying to create a simple webpage layout from scratch. I want all the elements of the page (nav, header, section, footer, etc.) to be centered while still keeping the nav bar on the left side. I've set ...

Generate a menu submenu allowing for interactive toggling and dynamic visualization of expandable/collapsible sections upon clicking, featuring visually

Looking for assistance in creating a dynamic menu with sub-menus that can expand upon clicking. The goal is to have an expandable menu structure where the user can click to expand or collapse certain sections. However, my current code is not functioning co ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

I have come to realize that my understanding of how Sass nesting works was misguided

Currently struggling with understanding Sass nesting. Any explanations on where I went wrong would be greatly appreciated, as this is a beginner-level issue for me. Thank you in advance. .header { display: flex; height: 10vh; background-color: #13192 ...

How can I remove the popover parents when clicking the confirm button using jQuery?

I am having trouble sending an AJAX request and removing the parent of a popover after the request is successful. I can't seem to access the parent of the popover in order to remove it, which is causing me some frustration. // Code for deleting w ...