eozzy
eozzy

Reputation: 68750

Calculate width dynamically (jQuery)

HTML:

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>

jQuery

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").outerWidth(true);
twoWidth = $(".parent .two").outerWidth(true);
$('.parent .three').width( parentWidth - oneWidth - twoWidth);

But the thing is, either DIV .one or .two may not exist some times, how do I modify the jQuery for it?

Thanks

Upvotes: 2

Views: 7357

Answers (3)

Anthony Serdyukov
Anthony Serdyukov

Reputation: 4328

Try this code:

var third = $('.parent .three');
var wantedWidth = third.parent().outerWidth(true);

third.siblings().each(function(){
    wantedWidth -= $(this).outerWidth(true);
});

third.width(wantedWidth);

Upvotes: 3

Tomas Vana
Tomas Vana

Reputation: 18785

Why don't you just check whether the result of $ function is empty ? ;) That way you can easily find out whether the div exists and simply set the width to 0 in that case, e.g.

oneDiv = $(".parent .one");
oneWidth = oneDiv.length == 0 ? 0 : oneDiv.outerWidth(true);

Upvotes: 4

John McCollum
John McCollum

Reputation: 5142

You can check if an element exists by checking its length property:

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").length ? $(".parent .one").outerWidth(true):0;
twoWidth = $(".parent .two").length ? $(".parent .two").outerWidth(true):0;
$('.parent .three').width( parentWidth - oneWidth - twoWidth);

Upvotes: 6

Related Questions