Brandon
Brandon

Reputation: 1081

get 50% position of HTML element

in a nut shell, I'm trying to write scroll tracking. However, I don't think my math is right for calculating the 50% offset of an html element(section).

Could someone look this over and tell me if it's wrong/right or if there might be a better way of calculating the 50% mark/offset.

// add the section elements into an array
var sections = $('section');


// define variables and arrays
var currentOffset = 0,
    lastScrollTop = 0,
    i = 0,
    offsets = [],
    sectionHeights = [];

// loop through sections and get 50% of height and add it to the .offset().top
for (i = 0; i < sections.length; i++) {
    sectionHeights.push($(sections[i]).height() / 2);
    offsets.push($(sections[i]).offset().top + sectionHeights[i]);
}

Upvotes: 1

Views: 96

Answers (1)

Markai
Markai

Reputation: 2098

Your math is right. The only thing you could do is simplify your code a little by using the jQuery .each function:

var currentOffset = 0,
    lastScrollTop = 0,
    i = 0,
    offsets = [];

$('section').each(function(){
    offsets.push($(this).offset().top + $(this).height() / 2);
});

Beware that if you have a dynamic page and the the sections positions or sizes get modified on client side you will have to recalculate the scroll positions.

Working fiddle

Upvotes: 2

Related Questions