¿Cómo identificar qué desplazamiento de elemento se está utilizando usando JavaScript?

Dados muchos elementos dentro del DOM, la tarea es averiguar qué elemento se está desplazando actualmente usando JavaScript.

Enfoque: este problema se puede resolver fácilmente usando JavaScript. Agregaremos el detector de eventos ‘scroll’ a todos los elementos requeridos. El evento de desplazamiento se activa cada vez que se desplaza un elemento en particular. Por lo tanto, podemos averiguar fácilmente qué elemento se está desplazando con la ayuda de este.

Ejemplo: en este ejemplo, creamos dos elementos desplazables y agregamos el detector de eventos ‘scroll’ a ambos. Tan pronto como se desplaza cualquiera de los elementos, se activa el evento de desplazamiento de ese elemento en particular.

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <title>How to identify which element
      scroll is being used using JavaScript?</title>
  
    <style>
      h1 {
        color: #2f8d46;
        font-weight: bold;
        margin: 40px;
      }
  
      #first {
        height: 200px;
        width: 400px;
        overflow-y: scroll;
        margin: 40px;
      }
  
      #second {
        margin: 40px;
        height: 200px;
        width: 400px;
        overflow-y: scroll;
      }
  
      #scrolled {
        margin: 40px;
      }
    </style>
  </head>
  <body>
    <h1>GeeksforGeeks</h1>
      
    <!--First element-->
    <div id="first">
      <h2>First element</h2>
        
<p>
        JavaScript is a lightweight, cross-platform 
        and interpreted scripting language. It is well-known 
        for the development of web pages, many non-browser 
        environments also use it. JavaScript can be used for 
        Client-side developments as well as Server-side
        developments. JavaScript contains a standard library 
        of objects, like Array, Date, and Math, and a core
        set of language elements like operators, control
        structures, and statements.
        History of JavaScript: It was created in 1995
        by Brendan Eich while he was an engineer at Netscape.
        It was originally going to be named LiveScript but
        was renamed. Unlike most programming languages, 
        the JavaScript language has no concept of input
        or output. It is designed to run as a scripting 
        language in a host environment, and it is up to 
        the host environment to provide mechanisms for 
        communicating with the outside world. The most 
        common host environment is the browser.
      </p>
  
    </div>
  
    <!--Second element-->
    <div id="second">
      <h2>Second element</h2>
        
<p>
        JavaScript is a lightweight, cross-platform 
        and interpreted scripting language. It is well-known 
        for the development of web pages, many non-browser 
        environments also use it. JavaScript can be used for 
        Client-side developments as well as Server-side
        developments. JavaScript contains a standard library 
        of objects, like Array, Date, and Math, and a core
        set of language elements like operators, control
        structures, and statements.
        History of JavaScript: It was created in 1995
        by Brendan Eich while he was an engineer at Netscape.
        It was originally going to be named LiveScript but
        was renamed. Unlike most programming languages, 
        the JavaScript language has no concept of input
        or output. It is designed to run as a scripting 
        language in a host environment, and it is up to 
        the host environment to provide mechanisms for 
        communicating with the outside world. The most 
        common host environment is the browser.
      </p>
  
    </div>
  
    <div id="scrolled">
      <h3>Element being scrolled: <span id="result"></span></h3>
    </div>
  
    <script>
        
      <!--Selecting required elements from the DOM-->
      const first = document.querySelector("#first");
      const second = document.querySelector("#second");
      const result = document.querySelector("#result");
        
      <!--Adding the scroll event listener-->
      first.addEventListener("scroll", () => (result.textContent = "First"));
      second.addEventListener("scroll", () => (result.textContent = "Second"));
    </script>
  </body>
</html>

Producción:

Publicación traducida automáticamente

Artículo escrito por arpit2205 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *