MysteryBlokHed MysteryBlokHed - 5 months ago 10
HTML Question

Get contents of a JavaScript function

I was trying to make a function in JavaScript that could set the

onClick
property of an HTML button.


So, say I have this as my function:

function myFunc(action){
document.getElementById('mybtn').setAttribute("onClick", action);
}


That would set
mybtn
's attribute
onClick
to the contents of the variable
action
(which should be a function).




So, if I ran the function like this:

myFunc(function(){
alert("Hello, World!");
});


Then the variable
action
would be set to

function (){
alert("Hello, World!");
}


If I ran
myFunc
as shown, it would successfully add the contents of
action
to the button's
onClick
attribute. The only problem is, if I click the button after
myFunc
has been run, I just get an error. It says:


Uncaught SyntaxError: Unexpected token (




I think that's because in the
onClick
attribute, you can't have a new function defined.


How can I get only what's inside the function in the variable
action
?

Answer

You can add an event listener instead of altering the attribute for onclick like this:

function myFunc(action) {
  document.getElementById('mybtn').addEventListener('click', action);
}

myFunc(function() {
  alert('foo');
});
<button id="mybtn">Foo</button>

Comments