Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda