Understanding the window.event property and its usage - javascript

I don't understand the motivation behind window.event or window.event.srcElement. In what context should one use this? What exactly does it represent in the DOM?

Here what w3school says about event object:
Events are actions that can be detected by JavaScript, and the event
object gives information about the event that has occurred.
Sometimes we want to execute a JavaScript when an event occurs, such
as when a 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 doesn't pass event to handler. Instead you can use window.event object which is being updated immediately after the event was fired. So the crossbrowser way to handle 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';
}

Not sure if this difference has been changed in newer browser versions but basically, "In the Microsoft event accessing model there is a special property window.event that contains the last event that took place." (from reference)
So, to write an event handler compatible across browsers you'd 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;
Reference:
http://www.quirksmode.org/js/events_access.html

function IndentifyMe(){
alert("You clicked on " + window.event.srcElement.tagName);
}
<body onclick = "IndentifyMe()">
Try this code, with lots of element in body tag, and try clicking different element

Events are the lifeblood of user interaction. Without events, you
couldn't interact with the page.
Event handlers are used to invoke some JavaScript when a certain action happens. If you want some
behavior to be triggered when the user moves their cursor over an element, you use the onmouseover
event handler.
"DOM Scripting: Web Design with JavaScript and the Document Object Model: Second Edition"

Related

Understanding Event Handlers in JavaScript [duplicate]

I don't understand the motivation behind window.event or window.event.srcElement. In what context should one use this? What exactly does it represent in the DOM?
Here what w3school says about event object:
Events are actions that can be detected by JavaScript, and the event
object gives information about the event that has occurred.
Sometimes we want to execute a JavaScript when an event occurs, such
as when a 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 doesn't pass event to handler. Instead you can use window.event object which is being updated immediately after the event was fired. So the crossbrowser way to handle 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';
}
Not sure if this difference has been changed in newer browser versions but basically, "In the Microsoft event accessing model there is a special property window.event that contains the last event that took place." (from reference)
So, to write an event handler compatible across browsers you'd 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;
Reference:
http://www.quirksmode.org/js/events_access.html
function IndentifyMe(){
alert("You clicked on " + window.event.srcElement.tagName);
}
<body onclick = "IndentifyMe()">
Try this code, with lots of element in body tag, and try clicking different element
Events are the lifeblood of user interaction. Without events, you
couldn't interact with the page.
Event handlers are used to invoke some JavaScript when a certain action happens. If you want some
behavior to be triggered when the user moves their cursor over an element, you use the onmouseover
event handler.
"DOM Scripting: Web Design with JavaScript and the Document Object Model: Second Edition"

addEventListener not attaching to the right scope

I am using the native DOM's addEventListener event like so:
const domElement = document.getElementById('ember464');
domElement.addEventListener('click', dosomething);
this._listeners.push({target: domElement, type: 'click', callback: dosomething});
this registered the event and stores it in a _listeners array so it can be cleaned up later. The good news is that this event does attach to the DOM but event though the target is clearly scoped to just the single button, the handler seems to fire whenever a click is detected anywhere on the document!
Am I doing something wrong?
p.s. here's the browser inspector looking at the _listener array ... note that highlighting the "target" does indeed point only to the button that I'm trying to target. AKA, the target is the DOM node, not the selector used to identify the node.
I've now looked at the debugger at the targeted DOM element and I see the following:
For anyone brave enough, here's a working demonstration of the code. The second button is triggered by the "click" event is the subject of this issue:
https://ui-animate.firebaseapp.com/
The full source code is here: link
Ok, the problem was in a bit of code I hadn't illustrated in the question. Modern browsers all support the DOM method addEventListener but in order to support older browsers who only have attachEvent I had added the following abstraction:
registerListener(target, type, callback) {
const addListener = target.addEventListener || target.attachEvent;
const eventName = target.addEventListener ? type : 'on' + type;
addListener(eventName, callback);
},
The problem with this is that the "this" context is lost in the call. So instead I changed to the following:
registerListener(target, type, callback) {
const listenerFunction = target.addEventListener ? 'addEventListener' : 'attachEvent';
const eventName = target.addEventListener ? type : 'on' + type;
target[listenerFunction](eventName, callback);
},

Why use event as a parameter in this JavaScript function?

What is the point of using event as a parameter in this JavaScript function?
<script type="text/javascript"›
function changeImage(event)
{
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagNamd == "IMG")
{
document.getElementbyId("mainImage").src = targetElement.getAttribute("src");
}
}
</script>
The event parameter in this function will give information about the event that triggered it when it is called by an event listener somewhere else in the code.
If nothing is passed as event (so, it wasn't called from a handler), it defaults to the global event variable of the window.
Included in the information from the event is an attribute called either target or srcElement, depending on the browser being used (hence the check on line 6), which holds the element that was the target of the event.
This element is then modified in various ways using DOM manipulation functions on the last few lines of the block.

Am I guaranteed to get an event object with a target property in a JavaScript event handler?

Just as the title says I'm curious if I'm guaranteed to get an event object inside of a Javscript event handler. The main reason I'm asking is that I've seen onClick event handlers that look like this.
function(e) {
if(e && e.target) {
//Code in here
}
}
Which seems wrong to me, but I know Javascript can have minor variances across browsers. Is there some time at which it's appropriate to check for the event object? Or the event target? It seems like you'd have to have a target to fire off an event.
No. Older versions of windows don't pass the event argument to the event handler. They have it in a global variable window.eventand the target is in .srcElement. Other than that exception, you should always get an event structure.
A work-around for the older versions of IE is this:
function(e) {
if (!e) {
e = window.event;
e.target = e.srcElement;
}
// code that uses e here
}
But, usually, this is addressed at a higher level by the function that you use to install event handlers. For example:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
window.event.target = window.event.srcElement;
return(fn.call(elem, window.event));
});
}
}
Depending on the browser compatibility they are looking to achieve, this may be an acceptable solution. However, for older version of IE, the event object is a part of the global window object. In order to get the target in that case you would want window.event.srcElement, as there is no target.
More info here on the event object for IE.

How can I make event.srcElement work in Firefox and what does it mean?

there is an if statement on my company's website that makes one web page imcompatible with firefox
if(event.srcElement.getAttribute("onclick") == null){
...code..
document.mainForm.submit();
}
I've commented out the if statement conditions and now its working with forefox. My question is, what is event.srcElement.getAttribute("onclick"), is it important, would it cause problems in the future. also, is there something similar i can replace the condition with so that it works on firefox?
Edit:
function gotoRDManagerPT(PTId, bDDetailId) {
if(!proceed()) return false;
var target = event.target || event.srcElement;
if(event.target.getAttribute("onclick") == null) {
document.mainForm.displayRDManagerPT.value = "true";
document.mainForm.PTId.value = PTId;
document.mainForm.bDDetailId.value = bDDetailId;
document.mainForm.submit();
}
}
srcElement is proprietary property originally coming from IE. The standardized property is target:
var target = event.target || event.srcElement;
if(target.onclick == null) { // shorter than getAttribute('onclick')
//...
document.mainForm.submit();
}
Also have a look at quirksmode.org - Event properties for more cross browser information.
Regarding the question what it is doing:
event.target / event.srcElement contains a reference to the element the event was raised on. getAttribute('onclick') == null checks whether a click event handler is assigned to element via inline event handling.
Is it important? We cannot say because we don't know what the ...code.. is doing.
In IE the event object is available in the window object already; in Firefox, it's passed as a parameter in the event handler.
Example
JavaScript:
function toDoOnKeyDown(evt)
{
//if window.event is equivalent as if thie browser is IE then the event object is in window
//object and if the browser is FireFox then use the Argument evt
var myEvent = ((window.event)?(event):(evt));
//get the Element which this event is all about
var Element = ((window.event)?(event.srcElement):(evt.currentTarget));
//To Do -->
}
HTML:
<input type="text" id="txt_Name" onkeydown="toDoOnKeyDown(event);"/>
As you notice when we called the function inside the html we have added a parameter event just in case the browser is Firefox.
I have read in an article that the event object in IE is called window.event and in Firefox we have to put it as a parameter.
In case you need it to be attached in the code:
document.getElementById('txt_Name').onkeydown = function(evt) {
var myEvent = ((window.event)?(window.event):(evt));
// get the Element which this event is all about
var Element = ((window.event)?(event.srcElement):(evt.currentTarget));
// To Do -->
};
Try quick fix as follows:
Include in code:
let target = event.target || event.srcElement;
and change
event.srcElement.XXXXX to target.XXXXX
this solves the issue with Firefox.

Categories

Resources