1

I am writing a Javascript pluggin where I am trying to get all the methods of an existing button on a website and assign it to a button I created myself and delete/hide the old button, so that the Website still works as expected, but with a new button-layout.

Is there a way to assign the functionalities of an existing button to a new one in Javascript?

I do not just want to change the layout of the existing button, because later I want to be able to assign functionalities from two existing buttons to a single newly created button.

I am trying to get the methods of the button I want to hide with the following function from:

How to get an object's methods?

function getMethods(obj)
{
    var res = [];
    for(var m in obj) {
        if(typeof obj[m] == "function") {
            res.push(m)
        }
    }
    return res;
}
T-Dog
  • 135
  • 8

1 Answers1

1

You can invoke click manually on the old button to cause its listeners to fire. Try something like:

// retrieve the button you want to replace
const button = document.querySelector('button');
const newButton = document.createElement('button');
button.insertAdjacentElement('afterend', newButton);
// Hide old button
button.style.display = 'none';
newButton.addEventListener('click', () => {
  // add additional functionality here

  // Run click listeners on old button
  button.click();
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320