Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda