Having trouble with the Jquery animate() function?

I recently developed a jQuery animation where clicking on specific buttons triggers a hidden div to slide from left: -650px; to left: 0px;. You can see an example by clicking here. However, I've noticed that when another button is clicked to reveal a different hidden div, the previous one doesn't return to its original position of left: -650px;; instead, it remains at left: 0;. Can anyone suggest what needs to be added in order to achieve this functionality?

HTML:

<div id="wrapper">
    <div class="top-block">
        <ul>
            <li><a id="one" href="#" class="proBtn">block</a>
            </li>
            <li><a id="two" href="#" class="proBtn">test</a>
            </li>
            <li><a id="three" href="#" class="proBtn">test</a>
            </li>
            <li><a id="four" href="#" class="proBtn">Lists</a>
            </li>
            <li><a href="#" class="proBtn">hello</a>
            </li>
            <li><a href="#" class="proBtn">test</a>
            </li>
        </ul>
        <!-- HOME SECTION -->
        <div id="one-bck" class="mid-block fadeInLeft" style="background:green;"></div>
        <div id="two-bck" class="mid-block fadeInLeft" style="background:red;"></div>
        <div id="three-bck" class="mid-block fadeInLeft"></div>
        <div id="four-bck" class="mid-block fadeInLeft"></div>
    </div>
</div>

JavaScript:

$(document).ready(function () {
    $('.proBtn').click(function () {
        $('li').removeClass('active');
        $('li a').removeClass('blue');
        $(this).parent("li").addClass('active');
        $(this).addClass('blue');
    });

    // Animation for Button One
    $('#one').click(function () {
        $('#two-bck, #three-bck, #four-bck').animate({
            left: '-650px',
            opacity: 0
        }, 500).removeClass('animated');
        $('#one-bck').addClass('animated').animate({
            left: '0px',
            opacity: 1
        }, 500);
    });

    // Animation for Button Two
    $('#two').click(function () {
        $('#one-bck, #three-bck, #four-bck').animate({
            left: '-650px',
            opacity: 0
        }, 500).removeClass('animated');
        $('#two-bck').addClass('animated').animate({
            left: '0px',
            opacity: 1
        }, 500);
    });

    // Animation for Button Three
    $('#three').click(function () {
        $('#one-bck, #two-bck, #four-bck').animate({
            left: '-650px',
            opacity: 0
        }, 500).removeClass('animated');
        $('#three-bck').addClass('animated').animate({
            left: '0px',
            opacity: 1
        }, 500);
    });

});

Answer №1

If you want to simplify things beyond just fixing the CSS and removeClass issue, consider streamlining the event handling process. Instead of attaching event handlers to individual IDs, which can be a maintenance headache since they all perform the same function, you can add a data attribute to the anchor tags like data-target="#three-bck" and then select them for animation within a single event handler.

Here is an example of how you can structure your HTML:

<ul>
  <li><a id="one" href="#" class="proBtn" data-target="#one-bck">block</a></li>
  <li><a id="two" href="#" class="proBtn" data-target="#two-bck">test</a></li>
  <li><a id="three" href="#" class="proBtn" data-target="#three-bck">test</a></li>
  <li><a id="four" href="#" class="proBtn" data-target="#four-bck">Lists</a></li>
  <li><a href="#" class="proBtn">hello</a></li>
  <li><a href="#" class="proBtn">test</a></li>
</ul>

And here is how you can handle the JavaScript logic:

$(document).ready(function () {
    $('.proBtn').click(function () {
        $('li').removeClass('active').find('a').removeClass('blue'); // Chain method calls for efficiency
        var $this = $(this); // Cache this reference
        $this.addClass('blue').closest("li").addClass('active');

        $('.mid-block.animated').animate({ 
            left: '-650px',
            opacity: 0
        }, 500, function(){
           $(this).removeClass('animated'); // Remove 'animated' class once animation finishes
        }).promise().done(function () { 
            $($this.data('target')).addClass('animated').stop(true, true).animate({
                left: '0px',
                opacity: 1
            }, 500);
        });
    });
});

Check out the Fiddle for a working example.

Answer №2

Eliminate the semi-colon following the 'px' in left:'-650px;'.

It should simply read as left:'-650px'.

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

Library for creating custom password input fields with a text type

We are currently facing an issue on our website where autofill is not working correctly due to having two password input fields - one for login and one for the password. Browsers are unable to remember the login information and paste the password into th ...

Validation for a datepicker embedded within a table

I'm facing a challenge and need some assistance. I want to validate if the "FROM (DATE)" is greater than the "TO (DATE)" without disabling the date selection, but instead prompting the user if the condition is not met. Any insights or solutions would ...

Develop rounded edges for a div element

I am interested in developing an HTML-based chart similar to the one shown below, but I am unsure of the steps to take. ...

Personalized Bootstrap 4 navigation bar tailored specifically for the application process

Seeking a customized progress nav-bar for my application, with a design similar to this: https://i.sstatic.net/ahDBa.png Discovered it on this website. Despite using the provided HTML and CSS, I'm unable to make it work with Bootstrap 4. HTML < ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Switch up the stylesheet in WordPress when an administrator is signed in

Looking for a way to incorporate conditional PHP code into my theme that will load a different stylesheet when either an admin or a specific user (ID=1) is logged in. Does WordPress have a function that can make this happen? There's a particular div ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

When implementing v-model on a v-dialog component, it causes the element within an array to

There is an array of apps with links, and a Dialog component that has v-model="dialog" to close it. However, after adding v-model to the v-dialog, the functionality of the apps is affected. The current app is passed as a prop to Dialog, but it always sends ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

What is the best way to search for a specific string within an Airtable record that may also have additional data included?

By utilizing the filterByFormula method in the airtable api, I am able to query and choose records that include a specific item (string). However, this query will only return the records that exclusively have that particular string. Referencing the airtab ...

Is it possible for cluetip to function on a hyperlink located in the top right corner of a webpage?

Currently, I am utilizing jquery cluetip for my project. There is a link located at the top right-hand corner of the page, and upon clicking it, I expect the tooltip to display at the bottom of the click location. However, instead of appearing at the desir ...

Database only accepts numerical data for insertion, rejecting any characters or alphanumeric entries

On a webpage, I have an input field through which I am passing the value into an ajax POST request. After logging everything in my JavaScript file and confirming that all is working as expected. In my PHP file, I retrieve the input value using $message = ...

Guide to using react-router for redirection and displaying messages

Is there a way in React to redirect after a successful login with a success message displayed on another component? I previously used flash messages, but they didn't integrate well with react-router and caused full page refreshes. Now that I am using ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

Ensuring that only one field is selected with mandatory values using Joi validation

Is there a way to create a validation rule utilizing Joi that ensures if valueA is empty, then valueB must have a value, and vice versa? My current approach involves using Joi for validating an array of objects with properties valueA and valueB. Below is ...

Avoid making GET requests when clicking on a link

[UPDATE] I need help troubleshooting an issue with my ajax request. Here is the code snippet that I am working on: <a href="" class="undo_feedback">Undo</a> When I click on the link, it triggers an ajax POST request, but I encounter an error ...

Struggling to employ JavaScript events when submitting a form to verify the fields

My goal is to create a form with fields that have real-time validation using JavaScript. I have achieved this by utilizing Java events in the following way: Text field onkeyup: This event sends a request to check for errors in the field every time a key ...

Using command line arguments to pass parameters to package.json

"scripts": { "start": "gulp", ... }, I have a specific npm package that I'm using which requires passing parameters to the start command. Can anyone help me with how to pass these parameters in the command line? For example, is it possible ...

Transferring a list of files from Callback folder

I am struggling with a function that is supposed to retrieve and list all the files in a specific folder. However, I am facing issues when trying to push out these files through an array. Something seems to be going wrong in my code as I receive an error w ...