How do you assign a JavaScript 'onclick' attribute dynamically?

As the other said you should assign a function.

Just wanted to point out that in this case you want to pass a value so you need to assign an anonymous function (or a named function defined inline) like

button.onclick = function() {otherfunction(parameter)};

If the function you want to assign does NOT require a parameter you can use it directly

button.onclick = otherfunction;

Note that there is no parenthesis in this case

button.onclick = otherfunction(); // this doesn't work

won't work as it will call otherfunction as soon as it is parsed


You have to assign a function, not a string.

backButton.onclick = function wastefulDuplicationOfBackButton () {
    navigate(-1);
}

you are assigning text to the onclick, try assigning a function.

backButton.onclick = function(){navigate(-1);};

Tags:

Javascript