0

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

1
  • 1
    myEvent is a handler, not an event. Commented Mar 13, 2011 at 21:07

3 Answers 3

3

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); };
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.