2

I need to get the height of three divs, add them together and see if the scroll position is great than that number. Right now I am able to get the height of one element, but how could I add others in?

Basically, I want to write "if scroll_top is greater than the height of div 1 + div 2 + 3"

var scroll_top = $(window).scrollTop();

if ((scroll_top > $('.nav-bar-fixed').height()) {
    alert('sometext');
}
hbowman
  • 307
  • 1
  • 6
  • 17

4 Answers4

14

Why not simply this ?

var h = 0;
$('#div1, #div2, #div3').each(function(){ h+=$(this).height() });
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

This should do the trick.

Working example on JS Bin.

HTML:

  <div class="nav-bar-fixed"></div>
  <div class="nav-bar-fixed"></div>
  <div class="nav-bar-fixed"></div>

CSS:

.nav-bar-fixed {
  height: 200px;
}

JavaScript:

var scroll_top = $(window).scrollTop(),
    $navBarFixed = $('.nav-bar-fixed'),
    totalHeight = 0;

$.each($navBarFixed, function() {
    totalHeight += $(this).height();
});

if (scroll_top > totalHeight) {
    alert(totalHeight);
}
Jeff Miller
  • 2,405
  • 1
  • 26
  • 41
2

Try this:

$(document).ready(function() {
var limit =$('.myEle1').height() + $('.myEle2').height() + $('.myEle3').height();
   $(window).scroll(function() {
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > limit ) {
           //do something.
        }
    });
 });​

Here is a fixed nav sample and source.

Community
  • 1
  • 1
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
1

You could implement this JQuery based function:

(function ($) {
   $.fn.sumHeights = function () {
      var h = 0;
      this.each(function() {
         h += $(this).height();
      });
      return h;
   };
})(jQuery);

And then call it like this:

$('div, .className, #idName').sumHeights();
Felixuko
  • 60
  • 5