tags:

views:

132

answers:

4

Hi All

Can someone explain to me how to get the height of one element, and then re-use it elsewhere on another element, using jQuery?

For example, to have 2 divs, 1 & 2, and to get the height of div 1, then have an on-click event on div 2 that animates it to the same height as div 1.

Cheers

A: 
$('#div2').click( function () {
  $('div2').height( $('#div1').height() )
}
);
code_burgar
+5  A: 

This would work:

$('#div1').click(function() 
{
    $(this).animate({
        height: $('#div2').height()
    });
});

Also, check the docs for more options: http://docs.jquery.com/Effects/animate

Reinis I.
+1 beat me to it (:
peirix
Cool - and is there some way to store the original height to re-use it later? For instance, store the height of div1, so if it went through some size changes for whatever reason, it could be animated back to it's original height then?
Sam
You could add a line like this prior to changing the height: window.original_height = $(this).height();It would add a variable in the global namespace storing the original height, but isn't really recommended because of possible conflicts. Instead, you should probably replace "window" with your own object.
Reinis I.
A: 

This is very basic jQuery, maybe you should have a look at the manual and API before asking this question?

An example in the API can be found at CSS > Height and Width > height(val):

$("div").one('click', function () {
  $(this).height(30)
         .css({cursor:"auto", backgroundColor:"green"});
});
Edwin V.
+2  A: 

Try this:

<div id="div-one" style="height:100px; background: #fb0">first div</div>        
<div id="div-two" style="height:50px; background: #fb0">second div</div>

<script type="text/javascript">
    jQuery("#div-two").click(function() {
        var desiredHeight = jQuery("#div-one").height();
        jQuery(this).animate({height: desiredHeight}, 1000);
    });
</script>
Alex
Great, I think I worded my question a bit badly, but this is exactly what I was looking for, so cheers.
Sam