Had asked this yesterday, but got no response, so putting this question out there again.
Say I have a page with many buttons / text links. I want the same custom event to be fired each time someone clicks on any of these links .
Is it possible to insert one bit of code to that any click on any button / link on that page will fire the event? Or do I have to insert individual event handler codes for each and every element?
I’m sure there must be an efficient way to do the former - can anyone guide here as to the exact steps, please?
The easiest method is by wrapping the action within a function and executing the function on each button.
For example:
function doStuff() {
console.log("doing stuff");
}
export function dropdown1_change(event, $w) {
doStuff();
}
export function input1_click(event, $w) {
doStuff();
}
//...
A more efficient yet complicated way is by adding the onClick event itself by code (this requires no interaction with the properties panel), and is achieved by a combination of two features:
Now, we can combine the two feature to create a simple loop that registers an event to all the buttons.
The following example will add an onClick event handler which executes doStuff() to every button that exists on the page:
$w.onReady(function () {
let btnArr = $w("Button"); //returns the list of buttons
btnArr.forEach(btn => {
btn.onClick((event, $w) => {
doStuff();
});
})
});
function doStuff() {
console.log("doing stuff");
}