Question

This is my html code:

<div class="masthead">
    <img class="img-responsive" data-src="holder.js/990x150/auto" alt="Generic placeholder image">
</div>
<!-- /container -->
<div id="menu-gora" class="navbar navbar-inverse  affix-top">

Img is responsive element, on my laptop it has got 150 px. When I try:

$(document).ready(function(){
        $('#menu-gora').affix({
          offset: {
            top: 150
          }
        });
    });

It works fine. But it doesn't work with:

top: $('.masthead img').height()

It starting "affixing" after passing 30 px. All the time. I need it to be responsive and I don't know what am I doing wrong :/

When I read the value with console.log($('.masthead img').height()), it shows me correct value. What is the problem?

Was it helpful?

Solution

as per the bootstrap docs, the 'proper' way to have a dynamic height is to have the value returned in a function, like

$('#menu-gora').affix({
    offset: {
        top: function () {
            return (this.top = $('.masthead img').height());
       }
    }
});

However! This does not account for dynamically sized content, so for instance if you have a carousel or accordion something that will change the height of where the affixed element is, you'll have to recalculate the new height. As far as I know there is no way to dynamically change the offset numbers. Right now what I'm doing is just reapplying the affix whenever the size changes (I have an unknown amount of collapses above my affixed menu).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top