CeceXX CeceXX - 4 years ago 113
HTML Question

Passing a value to a function in JavaScript

Say I have some HTML anchor elements and I would like to set a handler for each of them.

window.onload = function() {
// I select all of the anchors
var myAnchors = document.querySelectorAll("a");

// I iterate through the anchors and set a handler to each of them
for (var i = 0; i < myAnchors.length; i++) {
myAnchors[i].onclick = handleControl;
}
}

function handleControl(e) {
var id = e.target.getAttribute("id");
}


I'm unable to understand how setting an handler passes an argument to the
handleControl
function. In other words, how does
myAnchors[i].onclick = handleControl;
pass a value
e
to the handler?

I got this code from a JavaScript programming book.

Answer Source

It doesn't. Basically you're saying what function should be used when, at some point in time, a value becomes available. So for example, there you're saying that when the link is clicked, the function you specified, handleControl, should be called. The parameter e is passed to it by the browser, which represents information about the click event.

So think of it like:

  1. browser detects a click on the link
  2. it creates an "event object" that contains information about the event
  3. it invokes the handler function you specified with the "event object" as an argument. You can imagine it does something like anchor.onclick(event_info), where event_info corresponds to the e parameter you have on handleControl.

Keep in mind, this isn't necessarily exactly what's happening, but the point to answer your question is that the parameter comes from elsewhere (in this case, the browser), and is passed to an invocation of the function you specify.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download