简体   繁体   中英

Window height doesn't work on browser resize

I have this chunk of code that shows a "scroll to bottom" link when the page has scroll bars, or in other words when the browser height exceeds the users desktop resolution. Anyhow it works just fine if the browser window height is larger when the page initially loads but not if I resize the window after the page loads, then it wont trigger.

Any help would be appreciated.

$(function() {
    // Check to see if window has scrollbars
        if ($(document).height() > $(window).height()) {
            $('.scrollToBottom').animate({
                opacity : 'show',
                height : 'show'
            }, 'fast');
        } else {
            $('.scrollToBottom').animate({
                opacity : 'hide',
                height : 'hide'
            }, 'fast');
        }
    // Click event to scroll to bottom
    $('.scrollToBottom').click(function() {
        $('html, body').animate({
            scrollTop : $(document).height()-$(window).height()
        }, 1500, 'easeOutQuint');
        return false;
    });
});

This is because there is no "trigger" for it.

See this statement $(function() { .// code }) as when the document is ready, execute code.

What you need is another trigger for when the browser resizes:

$(window).resize(function (){
  if ($(document).height() > $(window).height()) {
    $('.scrollToBottom').animate({
        opacity : 'show',
        height : 'show'
    }, 'fast');
  } else {
      $('.scrollToBottom').animate({
          opacity : 'hide',
          height : 'hide'
      }, 'fast');
  }
})

And since you don't want to repeat yourself ou should write a function and call it inside these "triggers".

function showBar() {
  if ($(document).height() > $(window).height()) {
    $('.scrollToBottom').animate({
        opacity : 'show',
        height : 'show'
    }, 'fast');
  } else {
      $('.scrollToBottom').animate({
          opacity : 'hide',
          height : 'hide'
      }, 'fast');
  }
}

$(window).resize(function (){
  showBar();
})

$(function() {
  showBar();
})

These triggers are called events. For reference: https://developer.mozilla.org/en-US/docs/Web/Events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM