Jump to content

jQuery .animate: how to increase .height by a given percent

Recommended Posts

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
        var div = $("div");
        div.animate({height: '300px', opacity: '0.4'}, "slow");
        div.animate({width: '300px', opacity: '0.8'}, "slow");
        div.animate({height: '100px', opacity: '0.4'}, "slow");
        div.animate({width: '100px', opacity: '0.8'}, "slow");

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

<div style="background:red;height:50px;width:50px;position:absolute;"></div>


Hi All,


I've been working through W3 Schools tutorial on jQuery. I worked my way down to the topic on .animate (http://www.w3schools.com/jquery/jquery_animate.asp). For Example 1, of the "Use Queue Functionality", I thought I'd try experimenting with the code, and modified it to add a small red square on top of the large green one (see attached code).


I want the red square to change size as the green square changes size, but maintain its size relative to its larger sibling.


I can make this happen if I 'ID=' each square and give each the appropriate numeric value, but this isn't exactly flexible/generic.


I can use something like '+=100px' and '-=100px', but this clearly adds the same amount to both squares, and naturally the red square doesn't stay relatively sized to the green square.


Using something like '*=2.0' just silently fails.


Anybody have any suggestions?









Link to post
Share on other sites

You need to animate both of them individually, or at least start the animations at the same time. Get the current size of each of them and figure out the percent difference, and use that to calculate the new sizes for each of them.

Link to post
Share on other sites

Thanks. I take it then that there is no way to do a percent except manually. I was hoping I could devise a function (perhaps utilizing "this.height"). That, and maybe some concatenation magic (as in " ' " + (this.height*2) + "px'"). But no code wizardry I possible?!?

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...