Home > OS >  jQuery function load or resize inconsistent
jQuery function load or resize inconsistent

Time:02-25

I have a jQuery function which check whether a DOM element overflows the y-axis of the viewport, and applied a class to a different DOM element if that is the case. I want it to work on load and on resize:

    $.fn.overflowsViewport = function() {
        var elementTop = $(this).offset().top;
        var elementBottom = elementTop   $(this).outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop   $(window).height();
        return elementBottom > viewportBottom;
    };

    $(window).on('load resize', function() {
        if ($('#list .list').overflowsViewport()) {
            $("#post").addClass("shorter");
        } else {
            $("#post").removeClass("shorter");
        }
    });

This works on load, but only some of the time. Resize is fine.

I presume that something is causing the function to run before the page has fully loaded on some occasions. Usually a hard refresh will create the desired effect, but we can't expect the user to know/do that.

How can I make sure this function is loaded correctly so as to produce a consistent result? Or is timing not the issue here?

CodePudding user response:

Consider the following.

$(function() {
  $.fn.overflowsViewport = function() {
    var elementBottom = $(this).position().top   $(this).outerHeight();
    var viewportBottom = $(window).scrollTop()   $(window).height();
    console.log(elementBottom, viewportBottom);
    return elementBottom > viewportBottom;
  };

  function checkOverflow() {
    if ($('#list .list').overflowsViewport()) {
      $("#post").addClass("shorter");
    } else {
      $("#post").removeClass("shorter");
    }
  }

  $(window).resize(checkOverflow);
  checkOverflow();
});
.list {
  height: 450px;
}

.shorter {
  height: 120px;
  overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="post">
  <ul id="list">
    <li >Item 1</li>
  </ul>
</div>

This runs the checkOverflow function on load and when resize event is triggered on the Window.

  • Related