0

I'm trying to make a navbar affixable at the proper scroll position.

I have a #cover-section element and below it, an affixable navbar. The #cover-section element is resizable. when it gets resized, I want the affixing offset position to be modified as well, but the coverHeight variable doesn't seem to be updating. The coverHeight value initially is 0, and always remains zero.

How do I get the coverHeight variable within the .resize() function scope to actually modify the variable value that was declared outside of the event's scope?

$(document).ready(function() {
  var coverHeight;
  coverHeight = 0;

  $(window).resize(function() {
    $('#cover-section').height($(window).height() - $('#navbar').height());
    return coverHeight = $('#cover-section').height();
  });

  $('.affixable-wrapper').height($('.affixable-wrapper > .affixable').height());
  return $('.affixable-wrapper > .affixable').affix({
    offset: coverHeight
  });

});
ahnbizcad
  • 10,491
  • 9
  • 59
  • 85

1 Answers1

0

You are not assigning the values of these functions to the coverHeight variable. Resize doesn't have a return, and if it did you aren't returning it to anything. try

$(document).ready(function() {
  var coverHeight = 0;

  $(window).resize(function() {
      $('#cover-section').height($(window).height() - $('#navbar').height());
      coverHeight = $('#cover-section').height();
  });
});

If you are only binding to resize to fire affix, then:

    $(window).resize(function() {
        $('.affixable-wrapper > .affixable').affix({
        offset: $('#cover-section').height($(window).height() -  
$('#navbar').height());
        }); 
    });

You don't need the coverHeight var if you are only setting and calling it in the same function

atmd
  • 7,430
  • 2
  • 33
  • 64
  • so coffeescript's implicit return is the problem – ahnbizcad Jan 28 '15 at 09:15
  • I'm not getting any different behavior from this. I need the affixable portion code to reference the `coverHeight` variable. Should I be putting the "affixable" code elsewhere? – ahnbizcad Jan 28 '15 at 09:17
  • updated the answer, you dont need the var if you only want to bind to resize to call affix – atmd Jan 28 '15 at 09:22
  • Thank you, but this isn't working either. affix is an event listener, just like resize is. How would I use setTimeout to make sure the affix function is accessing the updated dom element (and the dom element's new sizes)? – ahnbizcad Jan 28 '15 at 09:32