/    Sign up×
Community /Pin to ProfileBookmark

How do I get rid of "this" ?

For years I’ve called javascript functions from onclick events inside html elements.

[code=html].
.
<div onclick=”someFunction()”>…</div>
.
.
[/code]

When I wanted to change the background color, or make some other change to the element I’d either give the element an ID and passed that in, or just pass the object reference of “this”

[code=html].
.
<div onclick=”someFunction(this);”>…</div>
.
.
<script>
function someFunction(obj) {
obj.style.backgroundColor = ‘red’;
}
</script>
[/code]

Is there a way go get rid of “this” ? Can “someFunction” be made to know what element caused it to be called from an onclick, onfocus, etc. event ?

I would love to get rid of the additional paramater.

to post a comment
JavaScript

16 Comments(s)

Copy linkTweet thisAlerts:
@Declan1991Jul 24.2008 — If it's defined inline, you cannot. If not, you can.<i>
</i>var el = /* Get element somehow, it depends on the code */document.getElementById("whatever");
if (window.addEventListener) {
el.addEventListener("click",function(e){alert(e.target);}[b],false[/b]);
}
else if (window.attachEvent) {
el.attachEvent("[b]on[/b]click",function(){alert(window.event.target);});
}
You can generalise the above code a lot (I normally write it as AEL(element, type, function)?.
Copy linkTweet thisAlerts:
@HoboScriptJul 24.2008 — If it's defined inline, you cannot. If not, you can.<i>
</i>var el = /* Get element somehow, it depends on the code */document.getElementById("whatever");
if (window.addEventListener) {
el.addEventListener("click",function(e){alert(e.target);}[b],false[/b]);
}
else if (window.attachEvent) {
el.attachEvent("[b]on[/b]click",function(){alert(window.event.target);});
}
You can generalise the above code a lot (I normally write it as AEL(element, type, function)?.[/QUOTE]


The problem with your code is that you are completely ignoring how he obtains the reference to the element. That is all which is useful. That addEventListener is irrelevant.

My solution would be to just keep the parameter in there, it's a single variable, not complicated to work with.

However~~~ If you really want to get rid of this, capture the HTML element from the event object which is created during that onclick creation.

See this:

http://www.quirksmode.org/js/introevents.html (scroll to the near bottom)
Copy linkTweet thisAlerts:
@Declan1991Jul 24.2008 — My solution would be to just keep the parameter in there, it's a single variable, not complicated to work with.[/quote]
Since the question is, how can I remove the parameter, that's not a solution.

However~~~ If you really want to get rid of this, capture the HTML element from the event object which is created during that onclick creation.[/QUOTE]
That is only created in IE when defined inline because it is global, unlike the W3C model, which does not have that as a global variable.

The Quirksmode links you were looking for were

[url=http://www.quirksmode.org/js/this.html#link3]this keyword and inline event registration[/url] and [url=http://www.quirksmode.org/js/events_early.html]inline event registration model[/url]
Copy linkTweet thisAlerts:
@HoboScriptJul 24.2008 — Since the question is, how can I remove the parameter, that's not a solution.


That is only created in IE when defined inline because it is global, unlike the W3C model, which does not have that as a global variable.

The Quirksmode links you were looking for were

[url=http://www.quirksmode.org/js/this.html#link3]this keyword and inline event registration[/url] and [url=http://www.quirksmode.org/js/events_early.html]inline event registration model[/url][/QUOTE]


Actually I think the event object is wrong, my mistake. If you read the link I posted I think it offers alternatives, being either this or srcElement.
Copy linkTweet thisAlerts:
@Declan1991Jul 24.2008 — Actually I think the event object is wrong, my mistake. If you read the link I posted I think it offers alternatives, being either this or srcElement.[/QUOTE]
srcElement is the event object, and this only works when it isn't defined inline because of the scope of the function. If defined as<i>
</i>element.onclick = function() {
alert(this);
};
it's different, but defining a function inline is like doing this<i>
</i>element.onclick = function() {
newFunction();;
};
function newFunction() {
alert(this); // expecting this to be the element.
}
Copy linkTweet thisAlerts:
@rnd_meJul 24.2008 — [CODE]<input onclick="hitme()" value ="hitme" />

function hitme(event){
if(!event){event=window.event}
that = even.target? event.target : event.scrElement;
alert(that.value); //shows hitme
}[/CODE]
Copy linkTweet thisAlerts:
@HoboScriptJul 24.2008 — [CODE]<input onclick="hitme()" value ="hitme" />

function hitme(event){
if(!event){event=window.event}
that = even.target? event.target : event.scrElement;
alert(that.value); //shows hitme
}[/CODE]
[/QUOTE]


was just about to write that ?

but yeah you got exactly what was i saying... note: it doesn't work for me right now, but i'll see if i can debug your idea.
Copy linkTweet thisAlerts:
@Declan1991Jul 24.2008 — function hitme(event){
if(!event){event=window.event}
that = even[b][color=red]t[/color][/b].target? event.target : event.s[b][color=red]rc[/color][/b]Element;
alert(that.value); //shows hitme
}

Ignoring the typos, it does not work when assigned inline as the quirksmode links I posted explain.
Copy linkTweet thisAlerts:
@HoboScriptJul 24.2008 — Ah shi..... because you need to pass the event as an object to get the reference... :-/

Shouldn't have ignored your quirksmode links, you were right.
Copy linkTweet thisAlerts:
@rnd_meJul 24.2008 — Ah shi..... because you need to pass the event as an object to get the reference... :-/

Shouldn't have ignored your quirksmode links, you were right.[/QUOTE]


you shouldn't. firefox passes the event obj as arguments[0] to the function. even if you don't supply a named parameter in your function definition, FF will pass the event ob to it anyway.

IE has to refer to the global event object.



at any rate, did you get it working?
Copy linkTweet thisAlerts:
@Declan1991Jul 24.2008 — Even if you don't supply a named parameter in your function definition, FF will pass the event ob to it anyway.[/QUOTE]
That is only true when it's like this<i>
</i>element.onclick = function(e) {
// Event argument passed
};
It is [b]not[/b] the case when it is inline, because the event isn't calling the function, the event is evaluating the code in the inline event handler string and [b]that[/b] is calling the function. It might as well be<i>
</i>&lt;input onclick="var a = 'hello'; alert(a);" value ="hitme" /&gt;


To try to illustrate the difference, putting an event handler [b]inline[/b] is very similar to doing this<i>
</i>element.onclick = function(e) {
hitme(); // Event argument is [b]not[/b] passed to this function
}
It will work in IE because event is global, and so can be gotten like this&lt;input onclick="anyfunction();" value ="hitme"&gt;

function anyfunction() {
anotherfunction();
}
function anotherfunction() {
alert(window.event.srcElement.value);
}
and if you really want to know, your code will work in W3C Event model browsers [b]if[/b] you do this<i>
</i>&lt;input onclick="hitme(arguments[0]);" value ="hitme"&gt;
Copy linkTweet thisAlerts:
@rnd_meJul 25.2008 — That is only true when it's like this<i>
</i>element.onclick = function(e) {
// Event argument passed
};

[/QUOTE]



yup, you are 100% correct.

i see now where the confusion around events comes from; i knew better and i failed to really think about my response (had wine with dinner).

thanks for pointing out the correct methods, and writing such a coherent explanation.

[B]

EDIT:[/B]


this does work however, and does shorten the inline code to avoid "this" :

[CODE]
<body>

<input type='button' value='tester' onclick="clickme()" />

<script type='text/javascript'>

function clickme(event){
if(!event){ event=clickme.caller.arguments[0] || window.event ; }
var t = event.target ? event.target : event.srcElement;
alert(t.value);
}

</script>
</body>[/CODE]


(tested in ff3 and ie7)
Copy linkTweet thisAlerts:
@Declan1991Jul 25.2008 — this does work however, and does shorten the inline code to avoid "this" :

[CODE]
<body>

<input type='button' value='tester' onclick="clickme()" />

<script type='text/javascript'>

function clickme(event){
if(!event){ event=clickme.caller.arguments[0] || window.event ; }
var t = event.target ? event.target : event.srcElement;
alert(t.value);
}

</script>
</body>[/CODE]


(tested in ff3 and ie7)[/QUOTE]

I like it, but since event will always be undefined, you can shorted (or clarify it maybe) to&lt;script type='text/javascript'&gt;

<i> </i>function clickme(){
<i> </i> var event = clickme.caller.arguments[0] || window.event ;
<i> </i> var t = event.target ? event.target : event.srcElement;
<i> </i> alert(t.value);
}

&lt;/script&gt;
Copy linkTweet thisAlerts:
@rnd_meJul 25.2008 — I like it, but since event will always be undefined, you can shorted (or clarify it maybe) to&lt;script type='text/javascript'&gt;

<i> </i>function clickme(){
<i> </i> var event = clickme.caller.arguments[0] || window.event ;
<i> </i> var t = event.target ? event.target : event.srcElement;
<i> </i> alert(t.value);
}

&lt;/script&gt;
[/QUOTE]


glad you like, i though it was clever. i left event open for overloading.

in fairness i should mention that it probably wouldn't work in opera or safari, so to be 100% compatible i guess we are stuck with passing "this" in DOM0 events.
Copy linkTweet thisAlerts:
@slaughtersauthorJul 25.2008 — Thanks "rnd me", "Declan1991" and everyone else who contributed to the thread. The above solution is what I needed and it seems to work in Safari 3.2.1 as well

Why I was needing this was because I was working on a tooltip script (one of the reasons I need to keep the event calls "inline"). It was a pain to have every tip call start with "this" as the first parameter i.e. tooltips(this,'tip message');, tooltips(this,'tip message2');, etc..

Now with "rnd me" and Declan1991's solution you can leave it out and the whole thing is shortened to a "tooltips('tip message');"

Here are some links to what I was doing:

Demo Page: http://stansight.com/WordPress/wp-content/uploads/2008/07/tooltips.html

JS File: http://stansight.com/WordPress/wp-content/uploads/2008/07/tooltips.js

Write Up: http://stansight.com/WordPress/2007/10/17/tooltips-for-forms/
Copy linkTweet thisAlerts:
@HoboScriptJul 25.2008 — Fixed your code to work in browsers that have deprecated caller *COUGH* OPERA *COUGH*

So now this script works in every browser on my computer except for IE 3. That means it works on IE 3 and up!

<i>
</i>&lt;html&gt;
&lt;head&gt;
&lt;script type='text/javascript'&gt;

<i> </i>function clickme(){
<i> </i>var event = (this.event) ? this.event : clickme.caller.arguments[0] || window.event;
<i> </i> var t = event.target ? event.target : event.srcElement;
<i> </i> alert(t.value);
}

&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;input type="button" value="Click me" onclick="clickme();" /&gt;
&lt;/body&gt;
&lt;/html&gt;
×

Success!

Help @slaughters spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...