JavaScript JavaScript and the DOM Responding to User Interaction The Event Object

What is event and target?

I am unable to understand what is a Event here, when passed into arguement and what is Target. Is it ok to say that Event can be click or keydown, whereas Target is on which element is clicked on. Maybe i am confused? Can someone explain to me in english analogy.?

2 Answers

Jonathan Dewitt
Jonathan Dewitt
8,101 Points

Yes, you are correct in your understanding. Event can be many things: click, mouseover, focus, keydown, etc. Target is the element that you are listening for the event to happen on. For example, with a button element, your event would be click and the <button> would be the target.

Jonathan Dewitt so imagine i got this to understand

document.addEventListener("click" , function(event){
        console.log("The" + event + "is clicked and" + event.target + "is targeted using tagname of " + event.target.tagName);
        console.log(event.target);
})

But the first line would print

The[object MouseEvent]is clicked and[object HTMLLIElement]is targeted using tagname of LI

but the second will be

LI

Why first line return a object?

Jonathan Dewitt
Jonathan Dewitt
8,101 Points

I think the result is different if you log the object alone versus being part of a string. If you want the log to be more specific, try using these:

console.log("The " + event.type + " is clicked and " + event.target.nodeName + " is targeted using tagname of " + event.target.tagName)

Jonathan Dewitt So in the video, when Guil do

if(event.target.tagName == ''BUTTON"){
let li = event.target.target.parentNode;
let ul = li.parentNode;
ul.removeChild(li);
}```

from what i undersand on the second line, the li get parentNode of button which is LI , and on line 3 it select the parent Node of li which is UL and on third line, it removes the child of UL from third line? So it goes up first and then down again?
Jonathan Dewitt
Jonathan Dewitt
8,101 Points

Yes it seems you understand it correctly.