Urgent -Multiple buttons, one function possible?

Hi all,

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?

Thanks a lot.
Naresh

I’m affraid that is not possible

Hi Naresh,

There are few methods to achieve this.

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:

The first, is the option to select multiple elements using $w.
See more info here on how to achieve that
http://www.wix.com/code/reference/$w.html#w

The second, is by adding an event handler by code.
It looks like this:

$w("#myElement").onClick( (event, $w) => {
 let targetId = event.target.id;  // "myElement"
} );

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

Hope this helps
Ido

did you get this I am wondering the same?