webworker
webworker

Reputation: 357

Calculate the height of an element based on the number of rows

I have an element that's height is being calculated by its content (a ul). At the moment the ul has two rows with three items in each. I am setting .elements position on screen using the following CSS;

.element {
position: absolute;
left: 30px;
top: -139px;
}

The markup for this is

<div class="element">
    <ul>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
    </ul>
</div>

In the future there will a need to add a third row to the ul which means the top positioning I am using will hide this new row (as the element div sits on top of another div), which is far from ideal.

I think i'll need to do this with jQuery, so regardless of how many rows get added, I don't need to change the CSS to fix this.

The WIP jQuery I have this far looks like:

var elemImgHeight = $('.element li img').height();
var toggles = $('.element li');
var numOfRows = math.ceil( toggles.length() / 3 );
var elemTopOffset = numOfRows * elemImgHeight + 10;

    if ($('.element li') => 7) {
        $('.element').css({ top:elemTopOffset })
    }

I'm not sure if I am on the right track with this, so could do with some pointers?

Thanks in advance.

Upvotes: 2

Views: 699

Answers (1)

Karim Magdy Mansour
Karim Magdy Mansour

Reputation: 316

Easy ... let's say you have this html structure:

<div class="element">
    <ul>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
        <li><img src="#" />Model</li>
    </ul>
</div>​​​​​​​

and you want to calculate the top position so that only the last li element is shown... using this:

var theElement = $(".element");
var topPosition = theElement.find("ul li:last").outerHeight()-theElement.outerHeight();
theElement.css("top",topPosition);

a sample is located here: http://jsfiddle.net/senegalo/eEya4/2/

Upvotes: 1

Related Questions