Shift a Div to the left prior to stretching it out

I am trying to achieve a smooth leftward movement and expansion animation for a div. Currently, I am experimenting with class switching on click events to transition between the desired states. However, I am facing difficulty in making the element first move left and then expand, as it tends to do both simultaneously or expand first before moving back when re-clicked.

My goal is to have a functionality where I can click to move the element left, then expand it, and finally re-click to revert back to its original position. Ideally, I would prefer implementing this in JQuery.

HTML:

<div class="box" id="box2">
  <h1 class="headline">BOX</h1>
</div>

CSS:

.box_clicked {
    height: 500px;
    width: 500px;
    background-color: rgba(0, 0 , 0, 0.8);
    transition: all 1s;
    -webkit-transition: all 1s;
    -moz-transition: all 1s;
   -o-transition: all 1s;
}
.box {
    height: 200px;
    width: 300px;
    background-color: rgba(0, 0 , 0, 0.8);
    position: relative;
    transition: all 1s;
    -webkit-transition: all 1s;
    -moz-transition: all 1s;
    -o-transition: all 1s;
}

.move-left {
    right: -100px;
    background-color: red;
}

Here is my jsfiddle link for reference.

Thank you!

Answer №1

To achieve the desired effect, we don't need an extensive amount of JavaScript code. Instead, we can utilize some clever CSS3 tricks. It's important to note that when using transitions on any properties, it is essential to define both the initial and final values. You can view a live example of this solution on JSFiddle: https://jsfiddle.net/dps6dwdv/1/

Below is the revised code snippet:

HTML

<div class="box" id="box2">
  <h1 class="headline">BOX</h1>
</div>

CSS

.box {
    height: 200px;
    width: 300px;
    background-color: rgba(0, 0 , 0, 0.8);
    position: relative;
    left: 0px;
    transition: left 1s, width 1s;
    -webkit-transition: all 1s;
    -moz-transition: all 1s;
    -o-transition: all 1s;

}
.box.active{
    left : 20px;
    width : 500px;
}

JavaScript

$('#box2').click(function(){
    $('#box2').toggleClass("active");
});

Answer №2

Achieve it all using CSS with a single animation effect

document.getElementById('button').addEventListener('click',function() {
  document.getElementById('box2').classList.toggle('animate');
})
.box {
  background-color: rgba(0, 0, 0, 0.8);
  position: relative;
  height: 200px;
  width: 300px;
}

input {
  display: none;
}

label {
  cursor: pointer;
  text-decoration: underline;
  color: #09c;
}

:checked ~ #box2, .animate {
  animation: foo 5s forwards;
}

@keyframes foo {
  50% {
    transform: translateX(100px);
    height: 200px;
    width: 300px;
  }
  100% {
    height: 500px;
    width: 500px;
  }
}
<input type="checkbox" id="checkbox"><label for="checkbox">checkbox</label> <button id="button">javascript</button>
<div class="box" id="box2">
  <h1 class="headline">BOX</h1>
</div>

Answer №3

Here's an example

let ready = true
$('#box2').click(function() {
  $('#box2').toggleClass("box box_clicked");
});

$('#box2').click(function() {
  if (ready) {
    $('#box2').addClass("move-left");
  }
  else $('#box2').removeClass("move-left");
  ready = !ready;
});
.box_clicked {
  height: 500px;
  width: 500px;
  background-color: rgba(0, 0, 0, 0.8);
  transition: all 1s;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -o-transition: all 1s;
}
.box {
  height: 200px;
  width: 300px;
  background-color: rgba(0, 0, 0, 0.8);
  position: relative;
  left: 0px;
  transition: all 1s;
  -webkit-transition: all 1s;
  -moz-transition: all 1s;
  -o-transition: all 1s;
}
.move-left {
  position: relative;
  left: 100px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" id="box2">
  <h1 class="headline">BOX</h1>
</div>

Answer №4

To accomplish this effect, you can utilize keyframe animations.

var square = document.getElementById('square1');
square.addEventListener('click', function() {
  square.classList.toggle('square_clicked');
});
@keyframes squareTransformed {
  50% {
    transform: translateY(100px);
  }
  100% {
    height: 600px;
    width: 600px;
    transform: translateY(100px);
  }
}

.square {
  height: 250px;
  width: 350px;
  top: 0;
  background-color: rgba(255, 0 , 0, 0.6);
  position: absolute;
}

.square_clicked {
  animation-name: squareTransformed;
  animation-duration: 5s;
  animation-fill-mode: forwards;
}
<div class="square" id="square1">
    <h1 class="title">SQUARE</h1>
  </div>

Answer №5

Are you anticipating something similar to this? Utilizing JQuery

var bind = true



$('#box2').click(function() {

  $('#box2').css({
    'right': '0px',
    'left': '0px'
  }).animate({
    'right': '150px'
  }, function(){ $(this).addClass("box_clicked").css({'height':'100px'})});

  
});

$('#box2').click(function() {
  if (bind) {

    $('#box2').css({
      'right': '0px',
      'left': '0px'
    }).animate({
      'left': '150px'
    },0, function(){  $(this).addClass("move-left").css({'height':'200px'})});
  }
  bind = !bind;
});
.box_clicked {
height: 100px;
width: 200px;
background-color: rgba(0, 0 , 0, 0.8);
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;
}
.box {
height: 100px;
width: 200px;
background-color: rgba(0, 0 , 0, 0.8);
position: relative;
transition: all 1s;
-webkit-transition: all 1s;
-moz-transition: all 1s;
-o-transition: all 1s;

}

.move-left {
right: -100px;
background-color:red;

 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" id="box2">
  <h1 class="headline">BOX</h1>
</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

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

The exported NextJS URL isn't functioning properly

Recently, I delved into the world of Next JS by following a tutorial on YouTube by Brad Traversy. In his guidance, I used next export to export the program and ran it using serve -s out -p 8000. While the page loads perfectly on localhost:8000, the issue a ...

Left-aligned collapsible navigation menu built with Bootstrap

Looking for a unique template or code snippet to implement the same menu as the one on this website: I want the menu to slide in from the left while darkening the rest of the screen, just like the site I referenced. Is there a bootstrap template that can ...

Executing JavaScript code from an external link

Currently, I am in the process of developing a horizontal parallax website. The functionality is working seamlessly; when I click on the menu, the slides smoothly transition horizontally and display the corresponding content. However, I have encountered a ...

When you use ReactDOM.render inside a <div>, it does not instantly generate HTML code

I am currently working with React version 16.7 and attempting to embed React components into a third-party JavaScript library (specifically, Highcharts) that requires me to output HTML from a function. This is the approach I am taking at the moment: funct ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

Experiencing a PHP Contact Form Problem - Unable to Identify the 400 Error Cause

Greetings! I'm fairly new to all this website creation stuff and I'm currently working on setting up a contact form from a template that I stumbled upon. Despite my best efforts in configuring the PHP code, I keep encountering a 400 response erro ...

Superbase Email Forwarding

Is it possible to create a dynamic redirect link in the confirmation email that directs users to a specific page after creating an account? For instance: If a user visits the website using a link such as www.website.com/project/1 or /project/2 etc. and t ...

The hamburger menu in Bootstrap collapses along with the navigation items when viewed on a mobile device

How can I resolve the issue of the hamburger menu icon collapsing with the nav-items when clicked? Navbar <header> <div class="container-fluid"> <div class="row"> <div class="col-12 col-sm-12"> ...

React-dnd enhances the functionality of the MUI tree view

I've been using a Material UI v4 Treeview with react-dnd and everything works smoothly. However, when I recently upgraded to MUI v5 Treeview, the drag functionality stopped working - the item is no longer draggable. After comparing the two TreeItem im ...

What is the best way to simulate DynamoDB promise functionality with Jest?

Looking for a solution without using any libraries (as they haven't worked in my case). How can I make it work for that promise returned by the dynamodb query? Check out the code to be tested below: const isUrl = require('is-url'); const ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

The location of errors is not displayed in VueJS stack traces

My Current VueJS Setup Check out the Source Code here I am working on a project using VueJS with webpack. I have chosen not to use the vue-loader plugin or .vue files. My project structure resembles a typical Javascript webpack project where I import vu ...

HTML list style with varying images at the same level in a ul tag

I am working on an Application that generates output with li tags. I am trying to find a way to apply different list-style-image for each li tag of the same level within the ul, while keeping the HTML code as simple as possible. Each li with a class of gre ...

Is there an issue with loading Vue list rendering due to Axios not returning the data?

Utilize the axios request api interface to fetch data and populate a list, but encounter a problem when trying to iterate through the properties of an object using v-for. Take a look at the javascript snippet below: var vm = new Vue({ el: '# ...

WordPress Plugin PrettyPhoto: Lightbox Positioning Adjusts Based on Gallery Item Location

Whenever I add more thumbnails to the gallery and they move onto a second row, the issue arises where the lightbox appears lower on the screen after clicking an image. How can I make sure the lightbox is always centered? The problem lies in the fact that ...

Applying style changes to the height on scroll event in Javascript for Chrome, Firefox, and Internet Explorer

I am working on triggering an event when scrolling to a specific height. I have code that successfully adds a style in Chrome, but it is not functioning properly in IE. Can anyone provide assistance? myID = document.getElementById("subnav"); var mySc ...