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

154
Vistas
How to use multiple elements in one set of code for javascript
$(document).ready(function() {
  $(".button1").click(function() {
    $("html, body").animate({
      scrollTop : $("#screen1").offset().top
    }, 800);
  });
})

$(document).ready(function() {
  $(".button2").click(function() {
    $("html, body").animate({
      scrollTop : $("#screen2").offset().top
    }, 800);
  });
})

...and so on

I wrote above code in javascript. If button is clicked, it scrolls to #screen position. However, I have several ".button"s and "#screen"s that basically has the same function. I don't want to repeat the same code so I've tried for in statement, but couldn't get it right. In what way can I avoid repeating codes in this situation?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Now, I cant see your HTML code, but my suggestion would be to add the event listener to a parent element to all the buttons and then add info about the button on the button itself. Here I'm using the attribute data-screen to hold info about the "screen".

UPDATE

I refined the jquery a bit. Using on() instead of click() so that I could remove the original if statement. When the event listener is on the parent element more buttons can be added dynamically and they will work as expected.

$(document).ready(function() {
  $("#buttons").on("click", "button", function(e) {
    var screenid = $(e.target).attr('data-screen');
    $("html, body").animate({
      scrollTop: $(`#screen${screenid}`).offset().top;
    }, 800);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttons">
  <button data-screen="1">Button 1</button>
  <button data-screen="2">Button 2</button>
  <button data-screen="3">Button 3</button>
</div>

<div>
  <div id="screen1"></div>
  <div id="screen2"></div>
  <div id="screen3"></div>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Assuming all the buttons & screens follow the naming convention .button${number} and #screen${number}, you can do this:

const numberOfSections = 5;

$(document).ready(function() {
  for (let i = 1; i <= numberOfSections ; i++) {
    $(`.button${i}`).click(function() {
      $("html, body").animate({
        scrollTop : $(`#screen${i}`).offset().top
      }, 800);
    });
  }
});
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