How can I use Jquery to slide one div over another and replace it in its position?

I am working on creating a unique animation using CSS and jQuery. The animation involves a green box sliding (or growing) over a fixed red box, and then toggling back so that the green box shrinks while the red one reappears.

One issue I encountered was using $("#green").css("width") causing the red box to be pushed, which is something I want to avoid in my animation.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

</head>

<body>
<style>
.green {
    width:400px;
    background-color:green;
    display:inline-block;
    height:320px;
}
.red{
    width:200px;
    background-color:red;
    display:inline-block;
    height:320px;   
}
</style>


<div>
<div id="green" class="green">eezez</div>
<div id="red" class="red">eezez</div>

    <script>
    $(function() {
        $("#action").click(function() {
            // toggle so green grows and takes red place (red does not move)
            // toggle so green shrinks and so red takes his initial place again
        });
    });
</script>

</div>
</body>
</html>

If you'd like to see the code in action, check out the fiddle link below:

http://jsfiddle.net/Sj575/

Answer №1

To achieve the desired layout, it is recommended to use a float instead of other methods. Here is an example code snippet:

Example Code

.blue {
    width:300px;
    background-color:blue;
    height:250px;
    float:left;
}
.yellow {
    background-color:yellow;
    height:250px;
}
#wrapper {
    width:500px;
    overflow:hidden;
}
<div id="wrapper">
    <div id="blue" class="blue">content1</div>
    <div id="yellow" class="yellow">content2</div>
</div>
<button id="toggleBtn">Toggle Blue!</button>

Answer №2

Insert this code snippet:

 $('#blue').fadeToggle("slow");

Next, include the following CSS style:

   .blue {
    width:500px;
    background-color:blue;
    display:inline-block;
    position:relative;
    height:280px;
}

JSFIDDLE LINK

Answer №3

Here's the solution I came up with:

Similar to user j08691, I also included float:left in both divs and added display:block and clear both to the button element to ensure it doesn't align on the left.

<body>
<style>
.green {
width:400px;
background-color:green;
float: left;
height:320px;
}

.red{
width:200px;
background-color:red;
float: left;
height:320px;   
}

#action{
display: block;
clear:both;
margin-top:2em;
}
</style>


<div>
    <div id="green" class="green">eezez</div>
    <div id="red" class="red">eezez</div>    
</div>

<button id="action" >Toggle Green !</button>

I created two separate functions to ensure that the button triggers only one event. Using preventDefault() method helps in achieving this. Through animate(), I increased the width of green while decreasing the red, eventually making the green disappear and red taking its place upon clicking 'action'.

<script>
    $(document).ready(function() {

        $("#action").one('click', toggleGreen);
            // toggle so green grows and takes red's position (red remains stationary)
            function toggleGreen(){
                $("#green").animate({
                    width:'600px'
                });
                $("#red").animate({
                    width:'100px'
                }).hide(2000);
                preventDefault();
            }

        $("#action").on('click', function(){
            // toggle so green shrinks back and red regains its original position
            $("#green").hide(2000);
            $("#red").animate({
                width:'600px'
            }).show(3000);
        })
    });
</script>

I trust this explanation is helpful!

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 could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

What could be causing the split() function to work on one condition but not on the other?

Background I recently undertook the task of converting a create-react-app application to nextjs. Most of my effort has been focused on ensuring that all existing components are compatible with server-side rendering. During this process, I encountered an ...

Combining two JSON arrays into a single array using Node.js

Two JSON arrays are available: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{sec:'A', class_name:'xyz' ...}] I am looking to combine these arrays into a single array. var finalObj = [{id:1, name: 'xxx' ...},{i ...

Execute the .click() function on an ajax element using a different element (not experiencing the issue of "click not working after ajax")

Currently, I am utilizing the small subscribe button created by campaignmonitor and I'm aiming to initiate a click on it using $("button").click(); in this manner $(document).on("click", ".trigger-cm", function(){ $("button").click(); }); Regrett ...

The performance of Mongoose queries is lagging, regardless of using lean

Utilizing MongoDB for data storage and Mongoose in Express for handling modifications, I believe my query processes should be optimized for speed. Correct me if I'm mistaken, but the dataset is large yet not overwhelmingly huge, especially since there ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

The MarkCompactCollector was unsuccessful in promoting the young object due to a failed allocation process

After successfully cloning a Git repository that houses a Vue project using the command git clone, I proceeded to run npm install in order to install all necessary dependencies, resulting in the creation of the node_modules folder. However, upon executing ...

Guide to retrieving table data using jQuery in a Vue.js function

I have a simple table set up in my Laravel blade file. When the edit button is clicked, it triggers a Vue method. <types-page inline-template> <div> <!-- table --> <table id="choose-address-tab ...

Tips for maintaining the webcam video in the center of the screen even when the height is set to 100% and the window is being resized

When using React, I encountered an issue with centering a webcam video while maintaining its height at 100% of the screen. Although the video fills the screen vertically correctly, adjusting the width of the window causes the video to lose its centered pos ...

What is the best way to create a distinct key for the key prop in my map function within a React component?

This is the initial code I have: class Board extends Component { static defaultProps = { nrows: 5, ncols: 5, chanceLightStartsOn: 0.25 }; constructor(props) { super(props); this.state = { hasWon: false, board: this. ...

Placing the overview right beneath the navigation bar in Bootstrap

I would like to create a large image similar to this: Just a big picture with oversized letters on it. I'm new to this, so please bear with me. Also, could someone guide me on how to achieve those big letters? It would be even more helpful if someone ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

Tips on choosing a button and applying custom styles with emotion styles in MUI

Looking to apply a margin-right to my button. Currently utilizing mui 5 with Button variant='contained'. I created a custom CSS style using the styled component in mui and targeted the Box. const Wrapper = styled(Box)({ display: 'flex&ap ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

Converting MSK time to SST time using JavaScript: A Handy Guide

My API returns time in the format: 07:00 PM This timestamp is based on MSK (Moscow Standard Time) and I need it converted to SST (Singapore Standard Time) using either JavaScript or an npm package. ...

Adjust the SVG to match the dimensions of the label, which may vary in both

How can I efficiently resize and embed SVG images into checkbox labels without using a viewbox attribute? Each SVG varies in height and width, making it challenging to find the best solution. .check__button { display: none; } .check__icon { display ...

I am experiencing an issue with my meteor insert not functioning when triggered by a click event. Oddly, no error messages are being

When a user clicks, data or an object from one collection is being transferred to another. The image below represents the individual object that is being moved. https://i.sstatic.net/PVX2q.png This click event is crucial in this process. Template.postsV ...

Colorful Paper Trail Logging

After stumbling upon a post on the internet, I discovered that Papertrail offers the ability to log using ANSI colors. This is particularly appealing to me as my node.js app generates numerous logs, and adding color helps me decipher the information during ...

Obtain form data as an object in Vue when passed in as a slot

Currently, I am working on developing a wizard tool that allows users to create their own wizards in the following format: <wiz> <form> <page> <label /> <input /> </page> <page> <label /> ...