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.
Related
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"
Currently working on a piece of code written by someone else for event handling. there are parts of the code that I am unsure about and if possible would like to get an explanation of what it all means.
if (div.addEventListener) {
div.addEventListener("click", handleClick, false);
} else if (div.attachEvent) {
div.attachEvent("click", handleClick);
};
function handleClick(e) {
var evt = e || window.event;
var target;
if (evt.target) {
target = evt.target;
} else {
target = evt.srcElement;
}
alert("You clicked on " + target.id);
};
I understand that it is checking to see if there is an event occurring, but why does it addEventListener twice as well as attachEvent twice? Also why does one return a false value and the other does not?
I am unsure as to what the second part of code is doing altogether, any possible explanation? I know it is the code that is called once the event(s) occur.
"addEventListener" doesn't works in IE(older Versions), in IE(older Versions) "attachEvent" works, So here check is maintained that which function is available, so it would be used.
if (div.addEventListener) {
div.addEventListener("click", handleClick, false);
} else if (div.attachEvent) {
div.attachEvent("click", handleClick);
};
Only one of these will happen (it's an IF statement). It first checks if the browser supports addEventListener.
The false parameter it passes in is the useCapture argument:
"The third, now optional, parameter in addEventListener is “useCapture”, which literally means fire the event at “capture” and not “bubble”. When an event is attached to an element, it will fire once the event has fully bubbled up to the document. However, if you set the useCapture flag to true, the event will fire on capture, and not wait for the event to fully bubble up the DOM tree." - from http://benhowdle.im/useCapture-demystified.html
The second part of the code is ran when the user clicks the DIV. It's again, checking to see if the browser supports certain event properties, to get the right element that was clicked.
why does it addEventListener twice as well as attachEvent twice?
It doesn't.
It tests to see if the property has a value, and if it does it calls the function stored in the property.
Also why does one return a false value and the pother does not?
Neither returns a false value. One has false passed in as the third argument. They are different functions and don't work the same way.
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.
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"
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.