Create a div element that initially aligns to the left, expands to the full width of the window, and then shrinks back

Hi there! I am currently diving into the world of javascript and jQuery, with a specific goal in mind. I want to create functionality where a div expands to the width of the window when clicked, then shrinks back down to its original size but switches alignment from right to left or vice versa. Although I have successfully achieved this effect starting from the right side, I've hit a roadblock when attempting to do the same from the left. Here's the code that works perfectly, but now I aim to reverse the direction.

<!doctype html>
<html>
<head>
    <title>Learning jQuery</title>

<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<script type="text/javascript" src="jquery.min.js"></script>

<style>
    #circle {
        height:200px;
        width:200px;
        background-color:red;
        border-radius:100px;
        position:absolute;
        right:0;
    }

</style>

</head>

<body>  

    <h1>Header</h1>

    <div id="circle"></div>

    <script>

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

        $(this).animate({

            width:"100%",

            }, 1000, function() {

                $(this).animate({

                    width:"200px",
                    left:"0"

                    }, 1000);

                });

        });


</script>

</body>
</html>

I attempted switching "left" for "right" in the code, but it resulted in the animation only happening on the left end without any movement towards the right. Additionally, experimenting with the position() function from the jQuery-ui plugin didn't quite yield the desired smooth transition, as it would grow, shrink, and abruptly jump back instead of flowing elegantly from one side to the other.

I'm open to any suggestions or guidance on how to achieve this effect seamlessly. Thank you in advance for your help!

Answer №1

Here is the solution to your issue:

 <!doctype html>
<html>
<head>
    <title>Using jQuery</title>

<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<style>
    #circle {
        height:200px;
        width:200px;
        background-color:red;
        border-radius:100px;
        position:absolute;
        right:0;
    }

</style>

</head>

<body>  

    <h1>Page Heading</h1>

    <div id="circle"></div>

    <script>

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

        $(this).animate({

            width:"100%",

            }, 1000, function() {
                if($(this).css('left') != '0px')
                $(this).animate({

                    width:"200px",
                    left:"0"

                    }, 1000);
                else{

                $(this).css('left','')
                $(this).animate({

                    width:"200px",
                    right:"0",                  

                    }, 1000);
                }

                });

        });


</script>

</body>
</html>

Answer №2

To make it work, avoid setting left:0 in the CSS

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

        $(this).animate({

            width:"100%",

            }, 1000, function() {

                $(this).animate({

                    width:"200px",
                    right:"0",


                    }, 1000);

                });

        });
  #circle {
        height:200px;
        width:200px;
        background-color:red;
        border-radius:100px;
        position:absolute;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Header</h1>

    <div id="circle"></div>

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

What is the best way to move table data content to a new line?

I have a table that spans the entire width of the screen, with 3 <td> elements inside. The content in the 2nd <td> does not contain any spaces and is quite long, causing it to expand beyond its allotted 70% width and disrupt the layout. Is ther ...

Having trouble retrieving data item with JQUERY's getJSON method

I am currently using a getJSON request in my code snippet: $.getJSON(url + "&callback=?", { postData: myText }, function(data) { alert('data : ' + data); }); During testing, I have an application running on "localhost:8080" where I ...

Setting up CORS in my React application with a Node.js backend

I created my react app using create-react-app. The app performs a POST call to an external API (elasticsearch) hosted on a different server not managed by me. When the user inputs data into the form and submits it, the onSubmit function calls getResponse() ...

Tips for structuring a JSON array of objects with the help of jQuery and Bootstrap

Currently, I am in the process of developing an online shopping application using Struts 2, MySQL, jQuery, JSP, Bootstrap, Gson, and Tomcat. In my Java entity, I have a class named Product, which is linked to a controller action that returns a JSON array ...

What is the method for displaying an asterisk in a select box option?

Is there a way to append an asterisk after the first option in a select element? Here is my html <select class="form-control textyformcontrol"> <option selected>Service area</option> <option>First Option</option> &l ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Obtain the details of a selected item in a list by tapping on it using Natives

I am wondering how to retrieve the context of a tapped item in a listview. For example, if there are three items in the list, how can I determine that the second item was clicked and access the data related to that item in the observable array? For instan ...

A versatile JavaScript function built to efficiently validate numerous forms across a webpage

Sorry for the simple query, but I'm still learning JavaScript. I have a script that checks if a text field is empty to validate user inputs. If it's not empty, a confirmation window pops up before submitting the form and uploading the information ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

Background and checked styles for radio buttons

Thank you in advance for any assistance you can provide. I am looking to create a unique radio button design. When the radio button is not checked, I want it to display as a simple white circle. However, once it is checked, I would like it to appear eithe ...

Arrangement of elements with no space at the top

Does the position.top of an element with a top-margin set to a value larger than 0 get calculated from the top-left point of the element or its margin when retrieving its position? ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

Discovering text on a webpage and extracting its XPath or CSS using Selenium and Java

Imagine a scenario where there is a page displaying various items on a table that changes in both order and quantity randomly. The task at hand is to locate a specific item labeled "Itemx" by its text, extract its XPath or CSS, and then use it in another ...

Is there a way to eliminate the underline in TextField components in Material-UI?

Is there a way to remove the underline from a material-ui TextField without using InputBase? I would prefer to stick with the TextField API, but have not been able to find a solution in the documentation. ...

What is the best way to vertically align an h1 heading in the content area of

I attempted to center my h1 within the body tag using the following code: h1 {margin:0 auto} http://jsfiddle.net/qPDwY/ However, it did not appear to center. What steps can I take to correct this issue? ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Scrolling without limits - cylindrical webpage (CSS/JS)

Is it possible to create a page that infinitely scrolls from top to top without going straight back to the top, but instead showing the bottom content below after reaching it? Imagine being able to scroll up and see the bottom above the top like a 3D cylin ...

What could be causing the div class to move downward in the CSS code?

I have posted a question, but unfortunately, no one has answered it yet. Here is my code snippet: * { margin: 0; padding: 0; } body { width: 100%; font-family: 'Cabin', sans-serif; background-color: #333; } .firstnav { ...

Comparing the benefits of using npm cache clean versus npm cache verify

Can you explain the distinction between the two commands below? npm cache clean npm cache verify Additionally, what is the purpose of the force option? I am particularly interested in how these commands work in a Windows development environment. ...

What is the best way to use AJAX to update multiple items with a common customer number on a SharePoint list?

Currently, I am facing an issue while attempting to update a SharePoint list using JavaScript/ajax. The script is running smoothly until it reaches the ajax function, where it encounters a failure. Specifically, it mentions that the ItemID is not defined, ...