Pergunta

When I affix my navbar element, which is below my header element, the navbar affixes prematurely, as if the image in the header did not exist.

The navbar is supposed to affix when the navbar reaches the top, not earlier. The code I used for this sets the offset to the scroll position of the navbar, but the problem is, this position is calculated as if the image in the header didn't exist.

I tried putting p tags around the image, explicitly set the image height to a fixed height as well as auto, set the display property to every conceivable value with no avail. I am not floating my image in the header. When I put extra lines of text in the header, the nav affixes to that height (the offset height of the navbar's affix detects the height of the text, but not images).


*edit: the fiddle works fine (this is the desired behavior). http://jsfiddle.net/gwho/8sAYW/ (this fiddle isn't exhibiting the problematic behavior for some reason).

the JS in coffeescript

ready = ->
$('.affixable').affix({
        offset: { top: $('.affixable').offset().top }
});
$('nav').height($('.affixable').height());
$(document).ready(ready);
$(document).on('page:load', ready);

**edit: but my local host behaves differently, as shown in the screenshot.

I think the issue may be that images are loaded last (before the navbar partial) in rails's asset pipeline... and the offset position of the navbar in the js code is calculated before the image is rendered... whereas in the JS fiddle, it doesn't have this issue.

If/how should I hold off running the javascript code, so that it runs after all the images are loaded?

Foi útil?

Solução

Solution!

The issue was that the javascript was running before the images were loaded (thereby resulting in an offset positioning that got calculated before the image was present). The solution was to load the javascript after everything else had been loaded by changing the last two lines of my coffee script:

ready = ->
$('.affixable').affix({
        offset: { top: $('.affixable').offset().top }
});
$('nav').height($('.affixable').height());
$(document).ready(ready);
$(document).on('page:load', ready);

to

ready = ->
$('.affixable').affix({
        offset: { top: $('.affixable').offset().top }
});
$('nav').height($('.affixable').height());
$(window).load(ready);
$(window).on('page:load', ready);

I don't know if this will happen on heroku, or other servers, but it sure helps to ensure it won't by using the latter code instead.


Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top