53

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?

Community
  • 1
  • 1
FatalKeystroke
  • 2,882
  • 7
  • 23
  • 35

4 Answers4

54

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>
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
23

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";
};
6

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/

Ashirvad
  • 2,367
  • 1
  • 16
  • 20
4

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

How does the "this" keyword work?

Community
  • 1
  • 1
Buzz
  • 6,030
  • 4
  • 33
  • 47
  • `this` is the object from which the function is called at call-time. There is no notion of "owner" in javascript. If the function is called without the use of an object, then `this` is the global object (`window` in a browser). For instance: `function f(){ console.log(this); }; o={a:f}; o.a(); var b = o.a; b();` – Pierre Oct 03 '17 at 17:56