Faites défiler automatiquement vers le bas de la page en JavaScript

Mehvish Ashiq 11 décembre 2023
  1. Utilisez la fonction JavaScript scrollTo pour faire défiler vers le bas
  2. Utilisez la fonction JavaScript scrollIntoView pour faire défiler vers le bas
  3. Utilisez la fonction JavaScript scrollTop pour faire défiler vers le bas
  4. Utilisez la fonction JavaScript ScrollingElement pour faire défiler vers le bas
  5. Utilisez la fonction JavaScript scrollBy pour faire défiler vers le bas
Faites défiler automatiquement vers le bas de la page en JavaScript

Notre objectif est de vous informer sur les différentes méthodes pour faire défiler automatiquement vers le bas de la page en JavaScript. Ce didacticiel vous apprend également à faire défiler des coordonnées spécifiques à l’écran avec et sans animation.

Utilisez la fonction JavaScript scrollTo pour faire défiler vers le bas

Code 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>

Code CSS :

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

Code JavaScript :

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

Le code donné ci-dessus sélectionne l’élément tag dont la valeur de l’id est bottompage. Chaque fois qu’on clique dessus, un événement se déclenche qui défile vers le bas de la page (défilement vertical) car x est défini sur 0 et y est défini sur document.body.scrollHeight soit 1655px.

La fonction scrollTo permet de faire défiler le document jusqu’aux coordonnées fournies de la page Web. Cette méthode fonctionne si la barre de défilement est visible et que le document est grand par rapport à l’écran.

Les deux paramètres de la méthode scrollTo() sont requis. Le paramètre x indique de combien de défilement horizontal en pixels et y environ verticalement en pixels.

Vous pensez peut-être à la façon dont la hauteur est calculée? Pour cela, vous pouvez lire ceci pour comprendre tous les calculs de hauteur.

Utilisez la fonction JavaScript scrollIntoView pour faire défiler vers le bas

Code 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>

Code CSS :

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

Code JavaScript :

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

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

Dans cet exemple de code, le querySelector obtient le premier élément qui a la valeur de l’attribut id comme heading_one et l’enregistre dans la variable hone. Après cela, il sélectionne le premier élément ayant la valeur de id comme list3 et le stocke dans la variable nommée listthree.

Chaque fois que vous cliquez sur le lien hypertexte Heading 1, la méthode navigatelistthree est exécutée. Cette fonction vous amène au troisième élément de la liste sous Heading 2, écrit comme List three in heading two.

La méthode scrollIntoView permet de faire défiler un élément dans la vue. Il est utilisé lorsque vous souhaitez qu’un élément particulier soit mis en surbrillance et que vous souhaitiez qu’il défile.

Cette méthode accepte un paramètre ; il peut s’agir d’une valeur booléenne ou d’un objet.

Vous pouvez utiliser scrollIntoView() pour sauter directement à l’élément où vous voulez être. Ou, vous pouvez utiliser la propriété comportement pour faire défiler en douceur.

Consultez ce lien pour en savoir plus sur les paramètres de la fonction scrollIntoView().

Utilisez la fonction JavaScript scrollTop pour faire défiler vers le bas

Code 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>

Code CSS :

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

Code JavaScript :

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

Tout d’abord, l’élément dont la valeur d’id est button est sélectionné si vous cliquez sur le bouton Scroll to Bottom. Ensuite, un autre élément dont la valeur de l’attribut id est boxcontent est sélectionné et enregistré dans la variable element.

Il vous amène à la fin de la zone de contenu, qui est défilable car la valeur de element.scrollHeight est affectée à element.scrollTop. Vous pouvez consulter plus de détails ici pour vous entraîner.

La propriété nommée scrollTop en JavaScript définit ou obtient le nombre de pixels de défilement vertical du contenu d’un élément.

La valeur scrollTop sera nulle si la propriété non-scrollable est associée à un élément. Ou l’élément n’a pas de débordement. Gardez à l’esprit que cette propriété se met à ZERO s’il y a des valeurs négatives.

Utilisez la fonction JavaScript ScrollingElement pour faire défiler vers le bas

Code 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>

Code CSS :

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

Code JavaScript :

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

Le code donné ci-dessus sélectionne l’élément de balise avec le id comme bottompage.

Un événement sera déclenché lorsque vous cliquerez sur l’élément dont l’identifiant vaut bottompage. Ensuite, la référence de l’élément racine (balise HTML) ou balise body (celle qui est disponible) est enregistrée dans une variable nommée scrollingElement.

De plus, la valeur de scrollTop est modifiée de 0px à 1310px en raison de l’attribution de la valeur de scrollingElement.scrollHeight à scrollingElement.scrollTop.

Utilisez la fonction JavaScript scrollBy pour faire défiler vers le bas

Code 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>

Code CSS :

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

Code 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);

Nous avons utilisé la fonction scrollBy dans la méthode setInterval pour animer le défilement dans cet exemple de code.

La méthode scrollBy est utilisée lorsque vous souhaitez faire défiler votre page jusqu’à un certain nombre de pixels. La fonction scrollBy prend deux paramètres, x et y (les deux sont obligatoires).

La méthode setInterval() appelle une fonction sur un intervalle donné. Le innerHeight renvoie la hauteur intérieure de la fenêtre (en pixels). Le scrollY renvoie le nombre de pixels que le document défile verticalement maintenant.

La propriété en lecture seule nommée offsetHeight renvoie la hauteur d’un élément (dans notre exemple, il s’agit de la balise body) sous la forme d’un entier. Cette hauteur comprend les bordures et le rembourrage vertical.

Le code ci-dessus fait défiler la page Web si la touche Enter est enfoncée. Et arrêtez le défilement de deux manières, soit la touche Enter est enfoncée à nouveau, soit la somme de window.innerHeight et window.scrollY est supérieure ou égale à 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

Article connexe - JavaScript Scroll