Understanding the window.event Property and Its Use

I do not understand the motivation of a window window.event or window.event.srcElement. In what context should this be used? What exactly does it represent in the DOM?

+8
javascript dom event-handling
source share
4 answers

Here w3school talks about the event object:

Events are actions that JavaScript can detect, and the event object provides information about the event that occurred.

Sometimes we want to execute JavaScript when an event occurs, such as when the user clicks a button.

You can handle events using:

 node.onclick = function(e) { // here you can handle event. e is an object. // It has some usefull properties like target. e.target refers to node } 

However, Internet Explorer does not pass the event to the handler. Instead, you can use the window.event object, which is updated immediately after the event fires. So the crossbrowser method for handling events:

 node.onclick = function(e) { e = e || window.event; // also there is no e.target property in IE. // instead IE uses window.event.srcElement var target = e.target || e.srcElement; // Now target refers to node. And you can, for example, modify node: target.style.backgroundColor = '#f00'; } 
+15
source share

I'm not sure that this difference has been changed in newer versions of the browser, but basically: "The Microsoft event access model has a special property window.event containing the last event that took place." (from the link)

So, to write an event handler compatible in different browsers, you need to do something like this:

 function doSomething(e) { if(!e) { var e = window.event; } var ele = e.target || e.srcElement; // get the clicked element // srcElement for IE, target for others } element.onclick = doSomething; 

Link: http://www.quirksmode.org/js/events_access.html

+6
source share
 function IndentifyMe(){ alert("You clicked on " + window.event.srcElement.tagName); } <body onclick = "IndentifyMe()"> 

Try this code with a lot of elements in the body tag and try clicking on another element

0
source share

Events are the lifeblood of user interaction. Without events, you could not interact with the page.

Event handlers are used to invoke some JavaScript when a specific action occurs. If you want a behavior that should fire when the user moves the cursor over an element, you use the onmouseover event handler.

"DOM Scripting: Web Design with JavaScript and the Document Object Model: Second Edition"

0
source share

All Articles