Desplazarse automáticamente al fondo de la página en JavaScript

Mehvish Ashiq 11 diciembre 2023
  1. Utilice la función scrollTo de JavaScript para desplazarse hasta la parte inferior
  2. Utilice la función scrollIntoView de JavaScript para desplazarse hasta la parte inferior
  3. Utilice la función scrollTop de JavaScript para desplazarse hasta la parte inferior
  4. Utilice la función ScrollingElement de JavaScript para desplazarse hasta la parte inferior
  5. Utilice la función scrollBy de JavaScript para desplazarse hasta la parte inferior
Desplazarse automáticamente al fondo de la página en JavaScript

Nuestro objetivo es educarlo sobre los diferentes métodos para desplazarse automáticamente al final de la página en JavaScript. Este tutorial también le enseña a desplazarse a coordenadas específicas en la pantalla con y sin animación.

Utilice la función scrollTo de JavaScript para desplazarse hasta la parte inferior

Código HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>Scroll Automatically</title>
  </head>
  <body id='main_body'>
      <button id="bottompage">Bottom</button>
      <div id="headingone">
           <h1>Heading One</h1>
           <img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		 background-of-software-developer-picture-id1294521676?                      
           b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			   alt="Programming Picture">
           <p>
           Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			 has been the industry's standard dummy text ever since the 1500s, when an unknown 			   printer took a galley of type and scrambled it to make a type specimen book. It has 			   survived not only five centuries, but also the leap into electronic typesetting, 			   remaining essentially unchanged. It was popularised in the 1960s with the release of 		   Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 				   publishing software like Aldus PageMaker including versions of Lorem Ipsum.
           </p>
      </div>
 	  <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
        <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			has been the industry's standard dummy text ever since the 1500s, when an unknown 			    printer took a galley of type and scrambled it to make a type specimen book. It has 			survived not only five centuries, but also the leap into electronic typesetting, 			    remaining essentially unchanged. It was popularised in the 1960s with the release of 		    Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 				publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </p>
     </div>
     <div id="headingthree">
       <h1>Heading Three</h1>
       <img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		 background-of-software-developer-picture-id1294521676?                      
       b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			   alt="Programming Picture">
 	   <p>
       Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem         	   Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		   unknown printer took a galley of type and scrambled it to make a type specimen         		   book. It has survived not only five centuries, but also the leap into electronic         	   typesetting, remaining essentially unchanged. It was popularised in the 1960s          		   with the release of Letraset sheets containing Lorem Ipsum passages, and more           		   recently with desktop publishing software like Aldus PageMaker including versions           		of Lorem Ipsum.
 	   </p>
 	</div>
 	<h1> Hi There! </h1>
 </body>
</html>

Código CSS:

button{
 float:right;
 background-color:yellow;
 color:red;
}

Código JavaScript:

document.querySelector('#bottompage').addEventListener('click', () => {
  window.scrollTo(0, document.body.scrollHeight);
})

El código dado arriba selecciona el elemento de la etiqueta cuyo valor de id es bottompage. Cada vez que se hace clic, se activa un evento que se desplaza hasta la parte inferior de la página (desplazamiento vertical) porque x se establece en 0 e y se establece en document.body.scrollHeight, que es 1655px.

La función scrollTo se utiliza para desplazar el documento a las coordenadas proporcionadas de la página web. Este método funciona si la barra de desplazamiento está visible y el document es grande en comparación con la pantalla.

Se requieren ambos parámetros del método scrollTo(). El parámetro x indica cuánto desplazarse horizontalmente en píxeles y y aproximadamente verticalmente en píxeles.

Quizás estés pensando en cómo se calcula la altura. Para eso, puede leer esto para comprender todos los cálculos de altura.

Utilice la función scrollIntoView de JavaScript para desplazarse hasta la parte inferior

Código HTML:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
    </p>
 
 	<a id="heading_one" href="javascript:void(0)">Heading 1</a>
 	<a id="heading_two" href="javascript:void(0)">Heading 2</a>
 	<a id="heading_three" href="javascript:void(0)">Heading 3</a>
 
	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-        	 background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
 	</div>
 	<div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-        	 background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
 		<ul>
           <li>List one in heading two</li>
           <li>List two in heading two</li>
           <li id="list3">List three in heading two</li>
           <li>List four in heading two</li>
           <li>List five in heading two</li>
           <li>List six in heading two</li>
           <li>List seven in heading two</li>
           <li>List eight in heading two</li>
        </ul>
    </div>
 	<div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
   </div>
   <h1> Hi There! </h1>
 </body>
</html>

Código CSS:

button{
 float:right;
 background-color:yellow;
 color:red;
}
a{
 display: block;
}

Código JavaScript:

let hone = document.querySelector('#heading_one');
let listthree = document.querySelector('#list3');
hone.addEventListener('click', navigatelistthree, false);

function navigatelistthree(e) {
  listthree.scrollIntoView({behavior: 'smooth'});
}

En este código de ejemplo, el querySelector obtiene el primer elemento que tiene el valor del atributo id como heading_one y lo guarda en la variable hone. Después de eso, selecciona el primer elemento que tiene el valor de id como list3 y lo almacena en la variable denominada listthree.

Cada vez que hace clic en el hipervínculo Heading 1, se ejecuta el método navigatelistatres. Esta función lo lleva al tercer elemento de la lista bajo Heading 2, escrito como List three in heading two.

El método scrollIntoView le ayuda a desplazar un elemento en la vista. Se usa cuando desea que se resalte un elemento en particular y desea que se desplace.

Este método acepta un parámetro; puede ser un valor Boolean o un object.

Puede usar scrollIntoView() para saltar de inmediato al elemento donde desea estar. O bien, puede utilizar la propiedad behavior para desplazarse sin problemas.

Consulte este enlace para obtener más información sobre los parámetros de la función scrollIntoView().

Utilice la función scrollTop de JavaScript para desplazarse hasta la parte inferior

Código HTML:

<div id="boxcontent">
 <div class="maincontent">
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
  </div>
</div>
<button id="button">Scroll to Bottom</button>

Código CSS:

#boxcontent {
 height: 200px;
 width: 300px;
 overflow: scroll;
 width: 300px;
}
.maincontent {
 width: 100%;
 height: 400px;
}

Código JavaScript:

document.getElementById('button').addEventListener('click', function() {
  var element = document.getElementById('boxcontent');
  element.scrollTop = element.scrollHeight;
});

En primer lugar, el elemento cuyo valor de identificación es botón se selecciona si hace clic en el botón Scroll to Bottom. Luego, se selecciona otro elemento cuyo valor de atributo id es boxcontent y se guarda en la variable element.

Te lleva al final del cuadro de contenido, que se puede desplazar porque el valor de element.scrollHeight se asigna a element.scrollTop. Puedes consultar más detalles aquí para practicar.

La propiedad denominada scrollTop en JavaScript establece u obtiene el número de píxeles que el contenido de un elemento se desplaza verticalmente.

El valor scrollTop será cero si la propiedad non-scrollable está asociada a un elemento. O el elemento no tiene desbordamiento. Tenga en cuenta que esta propiedad se establece en ZERO si hay valores negativos.

Utilice la función ScrollingElement de JavaScript para desplazarse hasta la parte inferior

Código HTML:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<button id="bottompage">Bottom</button>
 	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-             			technology-background-of-software-developer-picture-id1294521676?                   			b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			has been the industry's standard dummy text ever since the 1500s, when an unknown printer 		  took a galley of type and scrambled it to make a type specimen book. It has survived not 		   only five centuries, but also the leap into electronic typesetting, remaining essentially 		 unchanged. It was popularised in the 1960s with the release of Letraset sheets containing 		   Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 				PageMaker including versions of Lorem Ipsum.
 		</p>
   </div>
   <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        	 	Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen book.       		 It has survived not only five centuries, but also the leap into electronic           			typesetting, remaining essentially unchanged. It was popularised in the 1960s with        		  the release of Letraset sheets containing Lorem Ipsum passages, and more recently         		with desktop publishing software like Aldus PageMaker including versions of Lorem         		  Ipsum.
 		</p>
   </div>
   <div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen book.       		 It has survived not only five centuries, but also the leap into electronic           			typesetting, remaining essentially unchanged. It was popularised in the 1960s with        		  the release of Letraset sheets containing Lorem Ipsum passages, and more recently         		with desktop publishing software like Aldus PageMaker including versions of Lorem         		  Ipsum.
 		</p>
   </div>
   <h1> Hi There! </h1>
 </body>
</html>

Código CSS:

button{
 float:right;
 background-color:yellow;
 color:red;
}

Código JavaScript:

document.querySelector('#bottompage').addEventListener('click', () => {
  var scrollingElement = (document.scrollingElement || document.body);
  scrollingElement.scrollTop = scrollingElement.scrollHeight;
})

El código anterior selecciona el elemento de la etiqueta con el id como página inferior.

Se activará un evento cuando haga clic en el elemento cuyo valor de identificación sea página inferior. Después de eso, la referencia del elemento raíz (etiqueta HTML) o etiqueta body (lo que esté disponible) se guarda en una variable llamada scrollingElement.

Además, el valor de scrollTop cambia de 0px a 1310px debido a la asignación del valor de scrollingElement.scrollHeight a scrollingElement.scrollTop.

Utilice la función scrollBy de JavaScript para desplazarse hasta la parte inferior

Código HTML:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
        </p>
   </div>
   <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
        </p>
   </div>
   <div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
 		</p>
  </div>
 </body>
</html>

Código CSS:

body{
 background-color:lightgray;
}
h1{
 color:red;
}

Código JavaScript:

let scrollID;
let stopped = true;
let scrollSpeed = 2;  // 1 - Fast | 2 - Medium | 3 - Slow
let scrollInterval = scrollSpeed * 3;

function startScrolling() {
  let ID = setInterval(function() {
    window.scrollBy(0, 2);
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
      // Reached end of page
      stopScroll();
    }
  }, scrollInterval);
  return ID;
}

function stopScroll() {
  clearInterval(scrollID);
}

document.body.addEventListener('keypress', function(event) {
  if (event.which == 13 || event.keyCode == 13) {
    // It's the 'Enter' key
    if (stopped == true) {
      scrollID = startScrolling();
      stopped = false;
    } else {
      stopScroll();
      stopped = true;
    }
  }
}, true);

Usamos la función scrollBy dentro del método setInterval para animar el desplazamiento en este código de ejemplo.

El método scrollBy se utiliza cuando desea que su página se desplace a un cierto número de píxeles. La función scrollBy toma dos parámetros, x e y (ambos son obligatorios).

El método setInterval() llama a una función en un intervalo dado. El innerHeight devuelve la altura interior de la ventana (en píxeles). El scrollY devuelve el número de píxeles que el documento se desplaza verticalmente ahora.

La propiedad de solo lectura llamada offsetHeight devuelve la altura de un elemento (en nuestro ejemplo, es la etiqueta body) como un número entero. Esta altura incluye bordes y relleno vertical.

El código anterior desplaza la página web si se presiona la tecla Enter. Y deja de desplazarte de dos maneras, o se vuelve a pulsar la tecla Enter o la suma de window.innerHeight y window.scrollY es mayor o igual que document.body.offsetHeight.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Artículo relacionado - JavaScript Scroll