Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I'm creating a button dynamically using JavaScript and at the same time assigning attributes such as 'ID', 'type' etc and also 'onclick' in order to trigger a function.

All works fine apart from the assignment of the 'onclick'. When clicked, the button is not triggering the function as it is supposed to. the function I'm trying to run is 'navigate(-1)' as seen below.

Where am I going wrong?

Here's my code:

function loadNavigation() {
  var backButton;
  backButton = document.createElement('input');
  backButton.ID = 'backButton';
  backButton.type = 'button';
  backButton.value='Back';
  backButton.onclick = 'navigate(-1)';
  document.body.appendChild(backButton);
}
like image 497
Jack Roscoe Avatar asked Jun 09 '10 15:06

Jack Roscoe


2 Answers

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

like image 159
nico Avatar answered Oct 07 '22 16:10

nico


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

backButton.onclick = function(){navigate(-1);};
like image 20
jasonmw Avatar answered Oct 07 '22 17:10

jasonmw