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

Is there a way to dynamically insert page breaks in jspdf to ensure that tables do not split across multiple pages?

I am currently working on developing a website that can generate PDFs from database information, using PHP and MySQL to create tables with variable lengths. Sometimes, these tables may even span across multiple pages. If the first table takes up too much ...

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

Guide on implementing a Pug for loop using AJAX

For my school project, I am developing a web application similar to Tinder using Node.js, Express, and Pug. The main goal of the project is to provide potential matches to users based on either their proximity or common interests with the current user. Whe ...

Unable to fetch permissions for user:email via GitHub API

Currently, I am utilizing node-fetch to fetch an OAuth2 token from an OAuth2 GitHub App. The obtained token allows me to successfully retrieve user information from "https://api.github.com/user". However, I also require the email address, which necessitate ...

Discover the name of a color using its HEX code or RGB values

Is there a way to retrieve the color name from RBG or HEX code using JavaScript or JQuery? Take for instance: Color Name RGB black #000000 white #FFFFFF red #FF0000 green #008000 ...

Are you looking for a demonstration of "Creative Loading Effects" that triggers when the page is loaded?

I came across this demo for a preloader on my website called Creative Loading Effects, specifically the "3D Bar Bottom" effect, which I find very exciting. However, I noticed that it only loads when we press the button, and not automatically when the page ...

Updating elements within a subarray in JavaScript can easily be accomplished by accessing the

I need help updating nested array elements in JavaScript. I want to convert dates into a different format. How can I update the nested elements? array1 = [ { "week": [ "2019-05-06T16:00:00.000Z", "2019-05-07T16:00:00.000Z", "2019-05-08T16:00:00.000Z", "20 ...

The voracious nature of the `+` and `*` operators

There is a variable, const input = "B123213"; When using the following regex pattern, const reg = /\d+/; and executing String match function, console.log(input.match(reg)); The output returned is 123213, illustrating that the expression is gree ...

Designing a file upload progress bar with the help of jquery and ajax

I am looking to implement a progress bar for uploading files utilizing jquery and ajax. Here is the jquery code I have written: function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

StorageLimit: A new condition implemented to avoid saving repetitive values in the localStorage

Is there a way to store the text of an li element as a localStorage value only once when clicked? If it already exists in localStorage, a second click should have no effect other than triggering an alert. I'm currently using an if statement inside a ...

Dynamic Bootstrap User Authentication Form

Currently, I am in the process of constructing a login form for my web application and have opted to use Bootstrap for its styling. To ensure that the screen is responsive, I've integrated the following "Meta Tag" into the structure: <meta name="v ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

Having trouble with CSS webkit radial not working on iPad's Safari Mobile browser?

I'm feeling confused right now. I have this gradient code background-image: -webkit-radial-gradient(50% 65%, ellipse cover, #f2f2f4, #201935 55%); It's working on Safari when I change the User Agent to Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3 ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Innovative HTML5 Video Canvas Shapes

I'm currently working on creating a circular frame or canvas for live HTML5 Video. While I am able to round the corners using keyframes radius property, it results in an oval shape rather than a circle. My preference would be to utilize a div object ...

Modifying JavaScript prototypes on the fly can lead to troublesome issues

My curiosity has been piqued by the concept of dynamically changing a constructor's prototype in JavaScript, leading me to the findings above. It appears that an already constructed instance does not inherit the properties of the newly changed protot ...