- How to select the last element on viewport
- $(window).scroll(function () {
- $('.post-content p').removeClass("temp last")
- $('.post-content p').filter(":onScreen").addClass("temp")
- $(".temp").eq(-1).addClass("last")
- });
- // Store the offsets in an array
- var offsets = [];
- // Cache the elements to select
- var elements = $('.elem');
- // Cache the window jQuery Object
- var jWindow = $(window);
- // Cache the calculation of the window height
- var jWindowHeight = jWindow.height();
- // set up the variable for the current selected offset
- var currentOffset;
- // set up the variable for the current scrollOffset
- var scrollOffset;
- // set up the variable for scrolled, set it to true to be able to assign at
- // the beginning
- var scrolled = true;
- // function to assign the different elements offsets,
- // they don't change on scroll
- var assignOffsets = function() {
- elements.each(function() {
- offsets.push({
- offsetTop: $(this).offset().top,
- height: $(this).height(),
- element: $(this)
- });
- });
- };
- // execute the function once. Exectue it again if you added
- // or removed elements
- assignOffsets();
- // function to assign a class to the last element
- var assignLast = function() {
- // only execute it if the user scrolled
- if (scrolled) {
- // assigning false to scrolled to prevent execution until the user
- // scrolled again
- scrolled = false;
- // assign the scrolloffset
- scrollOffset = jWindowHeight + jWindow.scrollTop();
- // only execute the function if no current offset is set,
- // or the user scrolled down or up enough for another element to be
- // the last
- if (!currentOffset || currentOffset.offsetTop < scrollOffset || currentOffset.offsetTop + currentOffset.height > scrollOffset) {
- // Iterate starting from the bottom
- // change this to positive iteration if the elements count below
- // the fold is higher than above the fold
- for (var i = offsets.length - 1; i >= 0; i--) {
- // if the element is above the fold, reassign the current
- // element
- if (offsets[i].offsetTop + offsets[i].height < (scrollOffset)) {
- currentOffset && (currentOffset.element.removeClass('last'));
- currentOffset = offsets[i];
- currentOffset.element.addClass('last');
- // no further iteration needed and we can break;
- break;
- }
- }
- return true;
- } else {
- return false;
- }
- }
- }
- assignLast();
- // reassign the window height on resize;
- jWindow.on('resize', function() {
- jWindowHeight = jWindow.height();
- });
- // scroll handler only doing assignment of scrolled variable to true
- jWindow.scroll(function() {
- scrolled = true;
- });
- // set the interval for the handler
- setInterval(assignLast, 250);
- // assigning the classes for the first time
- assignLast();