Using jQuery to smoothly animate a sliding box horizontally

Is there a way to smoothly slide a div left and right using jQuery animation? I have been trying to achieve this by implementing the code below, which can be found in this fiddle.

The issue I am facing is that every time I click on the left or right button, the div resets back to its original position instead of continuing from where it currently is. What could be causing this behavior? I want the div to shift left or right based on its current position with each click.


    <div id="yellowbox"></div>
    <div id="left">left</div>
    <div id="right">right</div>

    <script>
        var left = $('#yellowbox').offset().left;
        console.log(left);

        jQuery(document).on('click', '#left', function(event) {
            $("#yellowbox").css({left:left}).animate({"left": (left -50)}, "slow");
        });

        jQuery(document).on('click', '#right', function(event) {
            $("#yellowbox").css({left:left}).animate({"left": (left +50)}, "slow");
        });
    </script>

    <style>     
    #yellowbox {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 0;
        right: 550px;
        background: yellow;
    }
    </style>

Answer №1

In order to fix the code, it is recommended to remove the call to .css as the code works perfectly fine without it. The issue arises because .css directly modifies the position with no effects, leading to unexpected behavior during animations.

Check out the DEMO here

var left = $('#yellowbox').offset().left;

$(document).on('click', '#left', function(event) {
    left -= 50;   // ensure to modify the variable here
    $("#yellowbox").animate({
        "left": left 
    }, "slow");
});

$(document).on('click', '#right', function(event) {
    left += 50;  // ensure to modify the variable here
    $("#yellowbox").animate({
        "left": left
    }, "slow");
});

Answer №2

Remember to update the left variable each time a click event occurs:

var leftPosition = $('#yellowbox').offset().left;
console.log(leftPosition);

jQuery(document).on('click', '#left', function(event) {
    $("#yellowbox").css({left: leftPosition}).animate({"left": (leftPosition - 50)}, "slow");
    leftPosition = $('#yellowbox').offset().left - 50;
});

jQuery(document).on('click', '#right', function(event) {
    $("#yellowbox").css({left: leftPosition}).animate({"left": (leftPosition + 50)}, "slow");
    leftPosition = $('#yellowbox').offset().left + 50;
});

Answer №3

Make sure to update your "left" variable each time you make a function call:-

var leftPosition = $('#yellowbox').offset().left;

    jQuery(document).on('click', '#left', function(event) {
        leftPosition = $('#yellowbox').offset().left;

        $("#yellowbox").css({left: leftPosition}).animate({"left": (leftPosition - 50)}, "slow");
    });

    jQuery(document).on('click', '#right', function(event) {
       leftPosition = $('#yellowbox').offset().left;

        $("#yellowbox").css({left: leftPosition}).animate({"left": (leftPosition + 50)}, "slow");
    });

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 transform an HTML table into an Excel file with several sheets?

Is there a way to transform multiple HTML tables into an Excel file with multiple worksheets? I need assistance with this task. You can find an example here function exportTablesToExcel() { var tableContent = "<table border='2px'>< ...

Stop iPhone body scrolling when fullscreen overlay is opened

My goal is to prevent the body from scrolling when my fullscreen overlay navigation is open. I have added a class show-nav to the body with the CSS attribute overflow: hidden, which works perfectly on desktop but not on iPhones. After researching similar ...

Improving conditional rendering in Mui <Cards> component by fixing state behavior

I have a situation where I want to display a Floating Action Button inside each Mui card when hovered over. However, I'm running into an issue with the hover state affecting all cards instead of just the one being interacted with. How can I ensure tha ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Position an element with absolute positioning to the right edge of a relative element

I have a situation where I need to align the end of a position absolute element with the end of a relative element, but the relative element's width is not fixed and may vary based on content. This scenario arises as I am creating a custom dropdown m ...

When viewing HTML "Div" on smaller screens, the full height may not be displayed properly

My setup includes two monitors: one is 24" and the other is my laptop's 12.5" screen. I have a red box (div) in my web application that displays full height on the larger monitor, but only partially on the smaller one. I'm puzzled as to why it s ...

Optimal method for managing errors in Flask when handling AJAX requests from the front end

I'm currently working on a React application that communicates with a Python Flask server. One of the features I am adding allows users to change their passwords. To do this, an AJAX request is sent from React to Flask, containing both the old and ne ...

React error: "Unable to locate property 'bind' within the undefined"

After reviewing several solutions, I'm still struggling to understand. Below is my code snippet: // userInputActions.js ... export function dummy() { console.log('dummy function called'); } ... // *userInputPage.js* import * as use ...

The animated loading image is taking an eternity to actually load

My website is loaded with heavy front-end features and I'm using a loading gif to help with the loading process. However, I've noticed that in Safari, there is a delay before the gif loads after the background does, which takes away from the inte ...

Guide on implementing image tag and source in Django template language system

I need to include a base64 encoded image in JSON format into a Django HTML template. What is the best way to do this? <img src="R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp(Some 64 bit image);base64 /> How can I properly translate this code snippet into my ...

Tips for personalizing the FileField in wtforms to function as an image button

I'm attempting to display an image from my project's directory as an icon instead of the standard "choose file" button. Unfortunately, my attempts thus far have been unsuccessful. Not only is the image not loading, but the original button is only ...

Inquiry to an outside domain

I need to send a request to an external domain, ensuring that the parameter is correctly sent to a PHP file on the external server. However, I'm facing an issue where "request.responseText" always returns empty. Any assistance in this matter would be ...

What could be the reason my checkbox won't check using jQuery?

Currently, I am using kojs within my Magento 2 project. I have implemented a method that successfully shows and hides an input box based on user interaction. However, despite the function working as expected, the checkbox does not display its checkmark. D ...

How to retrieve the chosen option from a drop-down menu created within a loop in a React application

I am seeking guidance on the best way to create multiple drop-down menus (<select>) using a loop, so that I can retrieve their selected values using a button. I have attempted to replicate what is currently in my code, hoping this information is suff ...

generate a series of nested divs within one another

I am looking to create a custom nested loop that will generate div elements based on the content of my h1 and h2/h3 tags. I understand this may have been covered in other inquiries, so any guidance would be appreciated :) Here is the initial HTML: <h1& ...

Facing an error response with the Javascript callout policy in Apigee. Any suggestions on fixing this issue?

This is the code snippet I'm using in my JavaScript callout policy var payload = JSON.parse(request.content); var headers = {'Content-Type' : 'application/json'}; var url = 'https://jsonplaceholder.typicode.com/posts'; va ...

What is the best method for transforming an HTML file into an ICS (iCal) file?

Hello there! I am interested in converting an HTML file (website) to an iCalendar file (iCal). Is this even possible? If so, how can it be achieved? Does anyone have any ideas or recommendations on how to proceed? Thank you in advance! ...

Applying scoped CSS styles to parent elements in HTML5

I've been delving into the details of the HTML5 specification, specifically regarding the scoped attribute on style elements. According to the specification: The scoped attribute is a boolean attribute. When used, it signifies that the styles are mean ...

Can this layout be achieved using DIV elements?

Struggling to create a unique HTML/CSS layout that extends beyond the center? Imagine a standard horizontally centered page, but with one div expanding all the way to the right edge of the browser window. This design should seamlessly adjust to window res ...

Sails.js Unidirectional Association

I'm currently working on establishing a relationship between two MySQL tables in sails js. I went through the documentation regarding this topic which can be found here. However, I encountered an error message: error: Sending 500 ("Server Error") re ...