Nima Parsi
Nima Parsi

Reputation: 2110

jQuery: Set auto height on page load

I need the class inside of the <li> tag to be auto height/adjustable to its <li>, however it wasn't possible with CSS(height:auto;height:100% and other options) so I tried jQuery but I'm a newbie so I tried what I've learned so far.
The following code does just what I need but I wasn't able to figure out how to set the auto height for the class on page load instead of .click function. Please note that I have many <li> tags with different sizes so (this) needs to be included.

$j("#accordion ul li").click(function () { 
  var current = $j(this).height() - 2;
  $j(this).find(".status-green").attr("style","height:" + current + "px");
});

Thanks in advance

Upvotes: 0

Views: 387

Answers (1)

Jasper
Jasper

Reputation: 75993

$j(function () {
    $('#accordion').find('.status-green').each(function (index, value) {
        var $value = $j(value),
            h      = $value.parents('li').height() - 2;
        $value.height(h);
    });
});

This will find and iterate through each .status-green element within the #accordion element when the DOM is ready ($j(function(){}); is short-hand for $j(document).ready(function(){});).

--Update--

This more closely resembles your code:

$j(function ($) {
    $("#accordion").find('li').each(function (index, value) { 
        var $value  = $(value),
            current = $value.height() - 2;
        $value.find(".status-green").height(current);
    });
});

If you pass $ as a argument in the first line then you can use $() rather than $j(). Also the .height() function assumes pixels if only a number is passed to it.

Upvotes: 1

Related Questions