Passing 'this' to an onclick event [duplicate]

Possible Duplicate:
The current element as its Event function param

Would this work

<script type="text/javascript">
var foo = function(param)
{
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

rather than this?

<script type="text/javascript">
var foo = function()
{
    document.getElementId("bar").innerHTML = "Not a button";
};
</script>
<button onclick="foo()" id="bar">Button</button>

And would the first method allow me to load the javascript from elsewhere to perform actions on any page element?


Solution 1:

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

Solution 2:

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>​

var foo = function()
{
    this.innerHTML = "Not a button";
};

Solution 3:

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/