Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
jQuery function load or resize inconsistent

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 class="list item">Item 1</li>
  </ul>
</div>

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!