2011/07/21

Detectar la parte inferior de la página con Javascript

Cómo saber si el usuario ha hecho scroll hasta el final de la página? (así de pronto se me ocurre que puede ser útil para EULAs y compañía).

Pues fácil, con este fragmento de código jQuery (que recomiendo se añada al final de la página o en el evento de domready)

Un código HTML de ejemplo sería el siguiente:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>Javascript - Detecting the bottom of the page</title>
 
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script type="text/javascript">
 
   $(window).scroll(function() {
 
    $('#notification2').html('document.height = ' + document.height);
    $('#notification3').html('window.pageYOffset + window.innerHeight = ' + (window.pageYOffset + window.innerHeight));
 
    if(document.height == window.pageYOffset + window.innerHeight)
    {
     // hit bottom
     $('#notification1').html('HIT BOTTOM');
    }
    else
    {
     $('#notification1').html('NOT AT BOTTOM');
    }
   });
 
  </script>
 
  <style type="text/css">
 
   body
   {
    margin:0px;
    padding:0px;
   }
 
   .box
   {
    width:400px;
    height:400px;
    margin:0px auto;
    background:#ccc;
   }
 
   .notification
   {
    position:fixed;
    color:#777;
    width:auto;
    height:auto;
    background:#ccc;
    padding:10px;
    font-family:Arial, Helvetica;
    font-weight:bold;
 
   }
 
  </style>
 
 </head>
 <body>
 
 <div class="notification" id="notification1">NOT AT BOTTOM</div>
 <div class="notification" style="top:50px;" id="notification2">document.height = </div>
 <div class="notification" style="top:100px;" id="notification3">window.pageYOffset + window.innerHeight = </div>
 
 
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 
 </body>
</html>

No hay comentarios:

Publicar un comentario