Dennis_M
Dennis_M

Reputation: 360

Can jquery return height of an element as a percentage?

$('#my_div').height('50%') will set the height but how can you retrieve the div's current height as a percentage?

Upvotes: 10

Views: 13271

Answers (5)

Marcello
Marcello

Reputation: 1289

Based on the other answer, for a fixed div like a panel, that is what worked for me:

    var h = Math.round(
        $('#my_div').height() /
        $(window).height() * 100
    );

Upvotes: 0

Bawm
Bawm

Reputation: 79

Try to hide the element you'll get it's percentage value.

<div id="a" style ="height: 300px; background: green; display: none;">
    a
    <div id="b" style ="height: 10%; background: blueviolet;">
        b
    </div>
    <div id="c" style ="height: 20%; background: cornflowerblue;">                        
        c
    </div>        
</div>
<script>
$(document).ready(function(){
    // height outside of event     
    $("#a").append($("#a").height());
    $("#b").append($("#b").height());
    $("#c").append($("#c").height());

    // height inside of event               
    $("*").click(function(){                
        $("#a").css("display", "block");
        $("#a").append($("#a").height());
        $("#b").append($("#b").height());
        $("#c").append($("#c").height());
    })
}) 
</script>

Notice that the value is different inside an event function.

Addition Notes:

The value reported by .height() is not guaranteed to be accurate when the element or its parent is hidden. To get an accurate value, ensure the element is visible before using .height(). jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery.

Source: jQuery height()

Upvotes: 0

Ken Redler
Ken Redler

Reputation: 23943

You can use .height(), which returns just the number (i.e, without the unit symbol). Perfect for percentage, which of course needs no units. From the docs:

The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

So you can try something like this:

var height_pct = Math.round( 
    $('#my_div').height() / 
    $('#my_div').parent().height() * 100
    );

Upvotes: 11

user1796099
user1796099

Reputation: 31

So Simple $("#eleid")[0].style.width

Upvotes: 0

Sachin R
Sachin R

Reputation: 11876

you can convert get height in px and convert them to percenatge

1em = 12pt = 16px = 100%

Upvotes: 1

Related Questions