1
$(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?

1
  • Try to use function each(). Commented Aug 11, 2021 at 18:02

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

I like the solution. I'd suggest to use $("#buttons button") (instead of the if statement) as a listener and const screenid = $(this).attr('data-screen') to get the id
@A_A thanks for the tips. I'm not into jquery. Not it is mush better.
You can use .data('screen') instead of .attr('data-screen'): api.jquery.com/data P.S. And $(this) instead of $(e.target).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.