Reputation: 4524
I'm just curious, why is this event being loaded instead of triggering itself on click .
window.onload=initAll;
function initAll(){
var divPath = document.getElementsByTagName("div")[0];
var theLink = divPath.getElementsByTagName("a")[0];
theLink.onclick = myEvent(theLink);
};
function myEvent (myMan){
myMan.innerHTML="You're my maan,bro!!!";
return false;
};
10x for your kind help BR
Upvotes: 0
Views: 88
Reputation: 25791
Because you are assigning the result of the function call myEventHandler(theLink)
to the theLink.onclick
property. What you are actually trying to do is the following:
theLink.onclick = myEventHandler
Which assigns a reference to the myEventHandler function to the theLink.onclick
property. The argument passed to that function will be an event object, from which you can determine which object was actually clicked. Alternatively, you can create a closure:
theLink.onclick = function(event) {
myEventHandler(event, theLink);
};
This way you get the event object and a reference to the object which you assigned the event handler to, which is what (I guess that) you were trying to do in your code.
Upvotes: 1
Reputation: 82943
Its because as per your code you are assigning the value returned by the function myEvent as the theLink eventhandler instead of the function itself. You should change the code to as follows:
window.onload=initAll;
function initAll(){
var divPath = document.getElementsByTagName("div")[0];
var theLink = divPath.getElementsByTagName("a")[0];
theLink.onclick = function(){ return myEventHandler(theLink)};
};
function myEvent (myMan){
myMan.innerHTML="You're my maan,bro!!!";
return false;
};
Upvotes: 1
Reputation: 888283
When you write theLink.onclick = myEvent(theLink)
, you're calling myEvent
and assigning the result to onclick
.
You need to create a separate function that calls myEvent
with a parameter, and assign that to onclick
:
theLink.onclick = function() { return myEvent(theLink); };
Upvotes: 3