Skip to content
Advertisement

How does an event object work in this code

window.onload = unblurMonaLisa;

function unblurMonaLisa() {
  var images = document.getElementsByTagName("img");
  for (var i = 0; i < images.length; i++) {
    images[i].onclick = showAnswer;
  } 
};

function showAnswer(eventObj) {
  var image = eventObj.target;
  var name = image.id;
  name = name + ".jpg";
  image.src = name;
};

The above code switches a blurred image for an image that is not blurred when said image is clicked. The code works just fine. My questions are about the eventObj that is passed to the showAnswer function. When is the eventObj created in this code? Is the scope of eventObj local? If I assigned the onclick event to two different variables would that create two eventObj and if so how would I access them individually?

Advertisement

Answer

When is the “eventObj” created in this code?

When the the event you are interested in happens, in this case a click, your callback function is automatically executed by the environment. When the callback function is executed, it is given an event object as an argument, which you can choose to ignore it in your function signature. (i.e. your showAnswer function could be like this function showAnswer() {...}). The event object is a regular object that holds information about the event that just happened.

Is the scope of “eventObj” local?

Yes, it is.

If I assigned the onclick event to two different variables

You cannot add two different callback functions by using .onclick. You should use addEventListener() if you want to add multiple callback functions to the same event.

would that create two “eventObj” and if so how would I access them individually?

The event object that would be created for that event would be just one, and it would be passed to all callback functions.

For more info on events read this: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Also check out the answer to this question, which is similar

UPDATE:

To answer to your comment:

the browser creates a unique Event Object every time an event occurs whether we have a handler listening for that event or not?

Correct.

We can pass this unique object to our handler

Correct again.

I noticed on your other post they used “e” in place of “eventObj”

You can name it whatever you want in your function. As long as you put something as your function parameter (function(e) {} for example) your function will accept the event object.

People usually name that parameter e, short for event, or event, to indicate what kind of thing is this parameter, but you can name it however you want, like any other parameter of any other function.

Advertisement