Ways to create a gradual movement for a div upon toggling a class

$(document).ready(function(){
  $("#toggle-btn").click(function(){
    $(".book").toggleClass("with-summary",1000);
  });
});
.book {
  height:500px;
  width:100%;
  position: relative;
  border:1px solid red;
}

.book-summary {
  position: absolute;
  left:-250px;
  top:0px;
  width:250px;
  height:100%;
  border:5px solid green;
  overflow-y: auto;
}

.book-body {
  position: absolute;
  right:0px;
  top:0px;
  left:0px;
  height:100%;
  border: 5px solid black;
  overflow-y: auto;
}


#toggle-btn:hover {
  cursor: pointer;
}



.book.with-summary .book-summary {
  left:0px;
}

.book.with-summary .book-body {
  left:250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="book">
  <div class="book-summary"></div>
  <div class="book-body">
     <button id="toggle-btn"> click me</button>
  </div>
</div>  <!-- book end -->

Although I specified "1000" in my code, the sliding of the div is still too fast. How can I make the div move slowly when toggling a class?

Answer №1

When you provide 100%, CSS transitions will not function properly. It is recommended to use a fixed value and implement the transition property:

* {font-family: 'Roboto';}

.show-hide {overflow: hidden; height: 150px; -webkit-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out;}
.show-hide.show {height: 300px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<a href="#" onclick="$('#show-hide').toggleClass('show'); return false;">Show / Hide</a>
<div class="show-hide" id="show-hide">
  <p>Apple Inc. is an American multinational technology company headquartered in Cupertino, California that designs, develops, and sells consumer electronics, computer software, and online services. The company's hardware products include the iPhone smartphone, the iPad tablet computer, the Mac personal computer, the iPod portable media player, the Apple Watch smartwatch, the Apple TV digital media player, and the HomePod smart speaker.</p>
  <p>Apple was founded by Steve Jobs, Steve Wozniak, and Ronald Wayne in April 1976 to develop and sell Wozniak's Apple I personal computer. It was incorporated as Apple Computer, Inc., in January 1977, and sales of its computers saw significant momentum and revenue growth for several years before going public in 1980.</p>
  <p>The company then went through periods of success and decline throughout the 1990s but transformed itself under the leadership of CEO Steve Jobs from around the turn of the century. Since then, Apple has become known for its innovation in design, especially with products like the iMac, iPod, iPhone, iPad, and MacBook. The launch of the iTunes Store in 2003 revolutionized the music industry, and the introduction of the App Store in 2008 created a new ecosystem where developers could distribute and monetize their apps.</p>
  <p>As of January 2022, Apple is one of the largest technology companies by revenue and market capitalization. It is also the world's largest technology company by total assets, and it has been ranked as the world's most valuable brand multiple times.</p>
  <p>Currently, Tim Cook serves as the CEO of Apple Inc., following Steve Jobs' passing in 2011.</p>
  <p>The company takes its name from the apple orchard belonging to co-founder Jobs.</p>
</div>

Note: Avoid using percentages in transitions or animations. Stick to fixed values for better results.

$(document).ready(function(){
  $("#toggle-btn").click(function(){
    $(".book").toggleClass("with-summary");
  });
});
* {
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.book {
  height: 400px;
  width: 100%;
  position: relative;
  border: 1px solid blue;
}

.book-summary {
  position: absolute;
  left: -200px;
  top: 0px;
  width: 200px;
  height: 100%;
  border: 3px solid orange;
  overflow-y: auto;
}

.book-body {
  position: absolute;
  right: 0px;
  top: 0px;
  left: 0px;
  height: 100%;
  border: 3px solid green;
  overflow-y: auto;
}


#toggle-btn:hover {
  cursor: pointer;
}



.book.with-summary .book-summary {
  left: 0px;
}

.book.with-summary .book-body {
  left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="book">
  <div class="book-summary"></div>
  <div class="book-body">
     <button id="toggle-btn">Click Me</button>
  </div>
</div>  <!-- End of book -->

Answer №2

To implement a smooth transition effect in CSS, you can utilize the following code snippets:

JavaScript

$(document).ready(function(){
  $("#toggle-btn").click(function(){
    $(".book").toggleClass("with-summary");
  });
});

CSS

.book {
  height:500px;
  width:100%;
  position: relative;
  border:1px solid red;
}

.book-summary {
  position: absolute;
  left:-250px;
  top:0px;
  width:250px;
  height:100%;
  border:5px solid green;
  overflow-y: auto;
}

.book-body {
  position: absolute;
  right:0px;
  top:0px;
  left:0px;
  height:100%;
  border: 5px solid black;
  overflow-y: auto;
}


#toggle-btn:hover {
  cursor: pointer;
}



.book.with-summary .book-summary {
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
    left:0px;    
}

.book.with-summary .book-body {
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
    left:250px;
}

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

Ensuring a @keyframe animation remains constant for the entire duration of the user's visit to the webpage using CSS

How can I create a continuous @keyframe animation that stays active for the duration of the user's visit to my webpage? I've implemented several color animations on my website, each with a specific duration. Is there a way to make these color ch ...

inject custom styles into a Material-UI styled component

Although I have come across similar questions, none seem to directly address my current situation. I am in the process of transitioning from MUI v4 to MUI v5 and have encountered various scenarios where a specific style is applied externally. For instance ...

Rod running from one end to another within a receptacle

I'm facing a challenge with my container (CardContainer) and its child elements. I want to create a bar that fills the space between the card image and the chevron, but I'm having trouble figuring out the best approach. How can I ensure that this ...

Unexplained quirks observed in AngularJS $watch during the initialization of a controller

I am working with a code snippet that utilizes AngularJS: var app = angular.module('Demo', []); app.controller('DemoCtrl', function ($scope) { function notify(newValue, oldValue) { console.log('%s => %s', oldValue, ...

Is it possible to stack images on top of each other on a webpage?

I'm looking to create a dress-up game website where users can click on different accessories to layer them on top of each other. It's a bit tricky to explain, but I've found some examples that demonstrate what I have in mind: This site is ...

Client-side rendering for NextJS server components is also supported

I am currently working with Material UI v5.11.16 in a nextjs environment using v13.3.0. I followed the official documentation setup for my nextjs project which can be found here. So far, I have successfully integrated Material UI components without having ...

Prevent a visitor from submitting the form again if it has already been submitted by the same visitor

Is there a way to prevent a visitor from submitting a form more than once? I've been thinking that cookies might be the solution. In my controller, I implement a cookie like this: class RatingsController < ApplicationController require 's ...

Managing a webpage using Xcode and Swift's UIWebView

Recently, I developed a straightforward application that guides users to a web-based platform. One of the app's pages allows users to search for store stock from various stores by manually inputting the store number or utilizing automatic location det ...

Display the component once the useEffect has been updated in React JS

I am currently working on developing a TV app and I am in need of creating a QR Code with a randomly generated code. This code should either be fetched from localStorage or generated on-the-fly if localStorage is empty. However, I am encountering an issue ...

Troubleshooting Ajax POST issues with Laravel

Looking for a way to submit a form with checkboxes representing user interests? Clicking a checkbox will send the checked interest value to the database "Followers" table, allowing the user to start following that interest. To handle this, I decided to cre ...

css code creates a stable block with a blurred transparent effect

I need assistance with creating a transparent fixed header using only CSS and no JS. I attempted to use ::before for creating a blur effect with a negative z-index, but so far, my attempts have failed. I know how to achieve this using jQuery, but I am spec ...

Tips for enhancing the flexibility of the owl carousel

I've been trying to make four items fit on a medium screen and two on a mobile device, but no matter what I do - adjusting widths, heights, columns, and responsive classes like col-6, col-md-3, col-lg-3 - nothing seems to work well. I could really use ...

Is it possible for URLs in CSS Custom Properties to be relative to the CSS file where they are defined?

I have a CSS library with resources like images and fonts that can be accessed from anywhere via CDN. I am trying to create URLs for these resources as Custom CSS Properties, relative to the library. <!-- https://my.server/index.html --> <link rel ...

"Rest API is not activating JavaScript on Android devices, whereas it functions correctly in web browsers

<?php $conn = mysqli_connect('localhost','eyukti_home_roc','4nYntQuCjPYR','eyukti_home_roc'); $user_id = $_GET['user_id']; $sql = mysqli_query($conn,"SELECT * FROM `vehicle_type` WHER ...

Is it possible for me to send transactions asynchronously using polkadot-js?

After thoroughly going through the official documentation, I stumbled upon a page discussing how to transfer using polkadot-js const transfer = api.tx.balances.transfer(BOB, 12345); const hash = await transfer.signAndSend(alice); I am curious if it' ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

Retrieve all items on the webpage using the pattern "_ followed by 10 random characters" through JavaScript

On my webpage, there is a table containing table rows in the following format: <tr id="_C15DKNWCSV">text</tr> I am attempting to scan the webpage and extract all table rows that have an id in the format: id="_(10 RANDOM CHARACTERS)" I want ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

Combining a standard JSS class with Material-UI's class overrides using the classnames library

I am exploring the method of assigning multiple classes to an element in React by utilizing the classnames package from JedWatson, along with Material-UI's "overriding with classes" technique. For reference, you can see an instance in MUI's docu ...