The idea is not for JS to "search for events", but to bind the buttons and destinations using a loop in an init script. Then all you need to do is to define the target of a button with an attribute, and JS will automatically take care of the rest.
Hence, you might wish to make scrollIntoView()
a global function, and have it accept the element you wish to scroll to as a param, like such.
function scrollIntoView(target) {
// Scroll code here
}
For scroll code example see here and here
Edit: somethinghere pointed out that scrollIntoView() is actually natively supported, so there is no need to write your own function anymore.
Say you have 3 buttons and 3 destinations in your DOM (I will use button
in place of a
for clarity's sake):
<button class="button_type_a" type="button">Scroll to destination A</button>
<button class="button_type_a" type="button">Scroll to destination B</button>
<button class="button_type_k" type="button">Scroll to destination C</button>
...
<div id="dest_A">Destination A</div>
<div id="dest_B">Destination B</div>
<div id="dest_C">Destination C</div>
First prepare the buttons:
- Add an arbitrary class (
goto_button
) to indicate the intended action of the button
- Add an arbitrary attribute (
target
) to indicate their respective destinations
Something like this:
<button class="button_type_a goto_button" type="button" target="dest_A">Scroll to destination A</button>
<button class="button_type_a goto_button" type="button" target="dest_B">Scroll to destination B</button>
<button class="button_type_k goto_button" type="button" target="dest_C">Scroll to destination C</button>
in which the value of target
is the id
of the destination.
Then in your JS, first find all your buttons:
var gotoButtons = document.getElementsByClassName("goto_button");
Then loop through your buttons, and for each one search and bind to their destination:
for (let btn of gotoButtons) {
let target = btn.getAttribute("target");
let destination = document.getElementById(target);
btn.addEventListener("click", () => {
destination.scrollIntoView();
});
}
Load this JS as an init script for your page and you should be all set.