Sam Skirrow Sam Skirrow - 7 months ago 19
Javascript Question

jQuery get the height of each div on a page with a certain class

I have a page with several divs with the class

.layers-content-widget
. Each div has differing amounts of content, so they differ in size, I want to make them all the same size as the page, regardless of how much content there is (unless of course there is more content than page height) Whilst still having the content sat in the middle of the div.

Here is my jQuery:

var pageHeight = $(window).height();
var sectionInnerHeight = $('.layers-content-widget').innerHeight();
$('.layers-content-widget').css('padding-top', ((pageHeight-sectionInnerHeight)/2));
$('.layers-content-widget').css('padding-bottom', ((pageHeight-sectionInnerHeight)/2));


The idea here is to get the page height and the content height (using innerHeight), divide this number by 2 and add it on as padding to the top and bottom - with the idea that the content will then sit in the middle of a full page section.

The issue I'm having is that this code works for the first div, but then applies the same amount of padding to all the other divs on the page. I know I need to use
this
but am unsure of how my final code should look

Answer

Your code is only running once and applying the calculated padding to each of the divs. What you need to do is parse all the divs in question and apply the padding to each individually...

var pageHeight = $(window).height();
$('.layers-content-widget').each(function() {
    var $this = $(this);
    var sectionInnerHeight = $this.innerHeight();
    $this.css({
        'padding-top': ((pageHeight - sectionInnerHeight) / 2),
        'padding-bottom': ((pageHeight - sectionInnerHeight) / 2)
    });
});

Here's the jQuery documentation for each, which is all you were really missing...

http://api.jquery.com/jquery.each/

Comments