What causes the discrepancy in animations between these two divs?

I am facing an issue with two divs that have different animations applied to them. Even though the animations are different, they are not working as expected. Here is the code snippet:

$(document).ready( function(){
  $('#show_hide_button').click( function() {
    $('#some_box').animate({ width: 'toggle' });
  });
});

You can view the whole code on jsfiddle http://jsfiddle.net/xLHb8/192/

I am confused as to why the first div is animating from right to left and left to right, while the second div always animates to the top left corner. Can anyone please help me understand why this is happening and suggest how I can make the second div animate the same way as the first div?

Answer №1

Make sure to include all relevant code details in your question along with providing the fiddle. Here is the CSS code snippet:

#some_box {
  background: #fc0;
  width: 25%;
  height: 200px;
}

.second img {  
  max-width:100%;
  max-height:100%;
}

.second {   
  width: 200px;
}

Accompanied by the following HTML:

<button id="show_hide_button">click me</button>
<div id="some_box"></div>

<div class="second">   
    <img src="http://piq.codeus.net/static/media/userpics/piq_66223.png" />; 
</div>

Note that the image is set to scale according to the parent container's size, resulting in the animation effect seen in the code snippet.

For a specific width collapse without affecting the image's height, you can set a fixed height for the image:

.second img {  
  max-width: 100%;
  height: 200px;
}

Additionally, you can handle both animations in a single click event:

$(document).ready( function(){
  $('#show_hide_button').click( function() {
    $('#some_box').animate({ width: 'toggle'});
    $('.second').animate({ width: 'toggle' });
  });
});

Link to the updated fiddle: http://jsfiddle.net/u1sdd8j5/1/

For a different effect where the image collapses to the left while maintaining its aspect ratio, a modified approach using CSS and jQuery is recommended:

#some_box {
  background: #fc0;
  width: 25%;
  height: 200px;
}

.second {
  width: 25%;
  height: 200px;
}

.second img {  
  max-width: 100%;
  max-height: 100%;
}

Updated JS code snippet:

$(document).ready( function(){
  $('#show_hide_button').click( function() {
    $('#some_box').animate({ width: 'toggle' });

    var $secondImg = $('.second img'),
        secondImgMargin = $secondImg.is(':visible') ? '50%' : 0;

    $('.second img').animate({
      width: 'toggle',
      marginTop: secondImgMargin
    });
  });
});

Link to the revised fiddle: http://jsfiddle.net/xwanm9ze/1/

Consider utilizing CSS3 transitions for a simpler implementation, ensuring to set up a class to toggle the animation and specifying the transform-origin property accordingly.

Answer №2

It appears that there is an issue with the dimensions of the elements in your code. The second div lacks a set width and height attribute, causing it to be controlled by the image within it. To resolve this, you can assign fixed dimensions to the second div.

  • As a solution, consider providing the second div with specific width and height values.

  • Additionally, you only need one $(document).ready function in your JQuery code.

$(document).ready(function () {
    $('#show_hide_button').click(function () {
        $('#some_box').animate({
            width: 'toggle'
        });
        $('.second').animate({
            width: 'toggle'
        });
    });
});
#some_box {
    background: #fc0;
    width: 25%;
    height: 200px;
}
.second img {
    width:100%;
    height:100%;
}
.second {
    width:200px;
    height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="show_hide_button">click me</button>
<div id="some_box"></div>
<div class="second">
    <img src="http://piq.codeus.net/static/media/userpics/piq_66223.png" />
</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

Controller return 400 error after Ajax request

My Ajax call is pointing to a controller function: <script type="text/javascript"> $(document).ready(function () { $('#AddNote').click(function () { $('#AddNote').addClass("disabled"); ...

Retrieving the body of a GET request using NodeJS and axios

Let me share my request with you: axios.get(BASE_URI + '/birds/random', {Stuff: "STUFF"}) .then(randBird=>{ const birdData = randBird.data const bird = { age: birdData.age, ...

Steps to add an SVG to a DIV when clicked

This script is fully functional and produces the desired results. var play = function(){ $( this ).click(function() { console.log( "Test" ); }); } I am looking to replace the console.log( "Test" ); with an SVG that will display in the cli ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

Is there a way for us to determine the time at which the user last took a screenshot or photo?

I am currently developing a website using Django and I have a unique requirement. I need to access the last image that a user has taken on their phone, without the image being shared by anyone else. The photo must be captured by the user's device itse ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

Tips for creating a TypeScript-compatible redux state tree with static typing and immutability:

One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner: interface StateTree { readonly subState1: SubState1; readonly subState2: SubState2; ...

How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately. Initially, I created a function that increases the column width when double-clicking on the header. Su ...

Create a responsive canvas with custom shapes

After designing a canvas with a gradient-filled circle, I encountered a challenge in making the canvas and the circle responsive to varying screen sizes. Initially, I attempted to use `vh` and `vw` units for the width and height of the canvas. However, ad ...

Utilizing the spread syntax for elimination

I want to remove a key. Check this out console.log(state); When I do, I get {1: {here is next object}}, next const { 1: deletedValue, ...newState } = state; console.log(newState); console.log(state); But then I end up with {1: {here is next object}} ...

Transforming HTML into a DOCX document

I am exploring all possible options for converting an HTML document to a DOCX file. Background : I have some simple documentation in HTML (just basic elements like H1, H2, P, IMG), and I want to transform it into Word documents. An ideal solution would ...

`Is there a way to manage date formats across all components using a single method in Angular?`

I need assistance with controlling the date format of dates displayed in different components using one typescript file. How can I achieve this? app.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', ...

Tips for managing a virtual URL within an img tag

I have a situation where I need to protect the src value of an img tag to ensure server security. One recommendation I received is to use a virtual URL approach: In this scheme, the img tag references a virtual URL like /uploads/myuser/mypict.jpg which isn ...

Resizing a scrollable list using React Refs and UseLayoutEffect

Essentially, my issue stems from having a scrollable list with a set maximum height of '100vh'. I also have a detail card beside the list that contains accordion components. When one of these accordions is expanded, it increases the height of the ...

Tips for handling line breaks across different platforms within a web application

I am currently developing a Web application and I have encountered some difficulties with the handling of newLine characters. My application allows users to create posts (similar to a forum) using the Markdown language. This means that the content is in p ...

Is it recommended for Protractor Page Objects to reveal ElementFinder?

Our team is currently debating whether or not to prohibit the exposure of "ElementFinder" and "ElementArrayFinder" in our Page Objects. The main point of contention is a quote by Simon Stewart. Page Objects Done Right - selenium conference 2014 (page.7) ...

Unusual behavior being exhibited by the background in an HTML5 canvas

I have an 800 by 100 image for the background and I'm trying to extract sections from it (like a sprite sheet) in order to create a background. I believe this method is efficient and allows me to experiment and learn how to generate backgrounds in the ...

Is there a way to extract information from an uploaded file in JavaScript without having to actually submit the file?

Looking for a way to extract data from a user uploaded file using Javascript without page submission? The goal is to process this data to provide additional options in a form on the same page. Any assistance with this would be highly appreciated. ...

Capturing Data from Tables and Saving it with Protractor

Imagine having a table structured like this <h2>HTML Table</h2> <table> <tr> <th>Company</th> <th>Contact</th> <th>Code</th> </tr> <tr> <td>Alfreds Fu ...

The transparency of the navigation menu is perplexing to me. I am unclear as to the reasoning behind it. I desire a

I am currently using a pre-made WordPress theme. Recently, I incorporated particles.js as the background for my website. The issue I am facing now is that my navigation menu is blending into the same color as the background. I have tried defining a separat ...