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');
}
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.
Why not simply this ?
var h = 0;
$('#div1, #div2, #div3').each(function(){ h+=$(this).height() });
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);
}
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();