It is said that if we use an event listener as:
document.getElementById("mybtn").addEventListener("click". function(/* event */){...});
then we don't need to mention event parameter inside the function's paranthesis. But if that is true then why don't the following work:
document.getElementById("mybtn").addEventListener("click". function(/* event */){ event.preventDefault()});
This is not true. It can't be implemented like this officially as long as event is not a reserved keyword.
Because people can then do:
document.getElementById("mybtn")
.addEventListener("click",function(troll,event) {
event.preventDefault(); // Boom! error.
});
and complain event is not working. Then it'll become necessary to document how people should not use the event object.
Some browsers might have a global event object. But implementations vary and it's not advisable to rely on such things.
History.
" Some posts say IE allows window.event to accessed without passing event"
When Microsoft corporation reverse engineered JavaScript off Netscape Corporation without consultation, they chose not to implement passing event as a parameter to event handlers.
Instead, IE implemented a window.event property where data for individual events could be accessed. It was during the browser wars when convincing programmers to write code for your browser that failed in the opposition's browser was seen as a good thing. Since JavaScript is single threaded, no re-entrancy problems were created by IE's approach.
You may still see event handler code starting out as
function handler(event)
{ event = event || window.event;
// handler code
}
which is a cross browser way of picking up IE's event object if not supplied to the handler function. At some point IE started passing the event object as a parameter in addition to setting it as a window property to maintain backwards compatibility in their browsers. It certainly works in IE 11 where
<span onclick="alert(arguments[0] === window.event);">click2</span>
alerts "true' when clicked, indicating event is passed as a parameter. In Firefox it is false on the basis window.event doesn't exist.
For current browsers name the first parameter of an event hander as event. If you want to support old versions of IE, use the cross browser code above. Never use 'window.event' by itself.
P.S. Experimenting with document emulation mode in IE11, IE versions <= 8 do not pass event parameter objects to handlers. According to this SO question neither does IE9 in quirks mode. Although IE8 may be the last operable version of IE under Windows XP, the browser is not supported by major commercial web sites in my country (Australia) which forces XP users to upgrade to a different browser. Whatever your case, do not use windows.event by itself.
document.getElementById("mybtn").addEventListener("click", function(event){ event.preventDefault()});
You are passing a callback function to the addEventListener. This function takes a parameter and you're using it.
Maybe changing it to another name and improving the indentation will help you understand this better.
document.getElementById("mybtn")
.addEventListener("click",
function(hello) {
hello.preventDefault()
});
To understand callback functions, try this
If you want use event directly then you have to pass event in that function from where you are calling that function. Otherwise you can create event like this:
document.getElementById("mybtn").addEventListener("click". function(/* event */){
var e=document.getElementById("mybtn");
e.preventDefault()
});
Related
I have a trouble in this part:
var ex = {
exampl: function(){
var ref=window.event.target||window.event.srcElement; // here
alert(ref.innerHTML); // (example)
}
}
This function is called this way:
document.body.childNodes[0].addEventListener('mouseover',ex.exampl,true);
Only Firefox says that window.event isn't defined...
I don't know what to do, to make it work. It works very well in webkit browsers and opera (I can't check it in MSIE and I don't care about it).
Why does it happen?
try getting the event using the parameter passed (named e in this case). i tested this and both window.event and the e is supported in chrome.
try checking for both, whichever exists
var ex = {
exampl: function(e){
console.log(window.event);
console.log(e);
//check if we have "e" or "window.event" and use them as "evt"
var evt = e || window.event
}
}
window.event is not a feature, it's a bug!
Quoting MDN:
window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.
And most importantly:
Not part of any specification.
window.event is non-standard, so don't expect any browsers to support it.
First parameter of callback function in element.addEventListener() is an Event object. Use it instead of window.event.
Because window.event doesn't exist in Firefox. That's because browser have different event models and you'll have to deal with their differences or use a library like jQuery not to have to deal with all the differences between browsers. Welcome to the DOM.
Chrome doesn't have it natively either. Rather than having every event trigger pass its own event object, IE dropped properties into window.event and handed that off. This worked since you're only ever dealing with one event at a time. What every browser should have is window.Event which is the actual constructor for event objects. If you're seeing 'window.event' anywhere but IE8 and below, try opening a console on a blank tab and logging or alerting it there. Chances are something is adding it manually on the page you're looking at.
If you look at crossbrowser normalizing code for event handlers, you'll often see:
if(!e){ e = window.event; }
That's event normalizing code handling older versions of IE. In modern browsers, e should be its own object being passed through arguments, not a reference to a property of window.
use jQuery..
let e = $.Event();
https://api.jquery.com/category/events/
window.event is available on Firefox from version 66 (release expected late octobre 2018).
This question already has an answer here:
Why is 'event' variable available even when not passed as a parameter?
(1 answer)
Closed 2 years ago.
I'm developing using mostly Chrome. I just discovered a bug, where the following snippet was working fine in Chrome, but not in Firefox.
Template.myTemplate.events({
"click input[type=checkbox]"(){
let context = event.target.dataset.context;
InspireTheWorldWith.call({context});
}
});
I could not quite believe my eyes, but essentially the variable 'event' was never assigned in the parameters of the event function. Yet this worked in Chrome without any issues. For the record, it clearly should be:
Template.myTemplate.events({
"click input[type=checkbox]"(event, template){
let context = event.target.dataset.context;
InspireTheWorldWith.call({context});
}
});
I'd like to read up more about this to really understand what is going on, but I'm struggling to find the approrpate 'keyword' to google. for.
Any suggestions?
For the record, I'm using Meteor 1.4, babel-runtime#6.18
It's nothing to do with Meteor, just Chrome: Chrome does this to support code written originally for Internet Explorer; in addition to passing the event to the handler, it also sets it as a global event variable.
Microsoft's "new" event handling in IE5 (or was it 5.5?) used a global event object and attachEvent/removeEvent. Then DOM2 came along (after IE6 had been released) and defined addEventListener/removeEventListener where the event handler recieves the event as an argument. Then years passed before Microsoft supported DOM2 (in IE9).
So when Chrome was coming up, they made the decision to provide a global event object to increase compatibility with IE-specific code. Mozilla chose not to originally, but does now; more in my answer here.
You can see it here — run this on Chrome:
document.getElementById("target").addEventListener("click", function(e) {
console.log("e === event? ", e === event);
}, false);
<div id="target">Click me</div>
As you can see, the global event object and the event object the handler receives are the same object.
I just can't understand what window.event() does in JavaScript. It is used without any definition. Same thing for document.event(). I also don't understand the difference between these two. Do they accept any arguments?
An event is something that is called when something happens, so for example click and keypress are events.
The reason however for window.event() is for cross browser compatibility. So here is some javascript:
object.onclick = function(e) {
// e holds all of the properties of the event
// You can access the event properties like so e.target
}
Internet Explorer however, doesn't deal with JavaScript the way other browsers do. So for Internet Explorer to deal with the same code as above we would write something on the lines of
object.onclick = function() {
alert(window.event.srcElement); // Same as e.target
}
Or you can combine them both together like so:
object.onclick = function(e) {
e = e || window.event; // Use e if it exists or e will be equal to window.event
var target = e.target || e.srcElement; // We then use the e.target property but if that doesn't exist we use e.srcElement
alert(target);
}
HTML 4 added the ability to let events trigger actions in a browser,
like starting a JavaScript when a user clicks on an element.
Here you can check a list of events that might be useful
I don't know if window.event is used now a days. It seems to be a very generic one. Rather you can use more specifics window events like onerror, onload, onresize, onstorage etc
Before using them be sure to check for browser compatibility.
Thank you.
The "informal" window.event is not a "method" of "window", and thus is not called with parenthesis and/or arguments. Instead it is a Microsoft IE only informal global browser "property" of Window used to locate the current active event object (only one event can be active at a time since browsers are single threaded). For more on what an event object might offer, see http://www.w3schools.com/jsref/dom_obj_event.asp
Window.event is only needed before IE9, since IE9+ and other browsers pass the event object as the first parameter to the event handler that has been registered. A standard browser handler "function onclick(e)" would access information about the current event by using the passed in local parameter "e" (or whatever the handler author named it), while prior to IE9 that handler's parameter "e" would be undefined requiring the handler to access window.event instead.
In practice, this means that when handling an event, "old IE" tolerant code examines the "event" passed in and if not found looks for window.event: function handler(e) {var e=e?e:window.event;}
To try and be as helpful as possible, as far as I am aware (and can find), window.event is informally accepted as part of IE but document.event is not and thus would only work through even less than informal IE tolerance (and is even more likely to vary based on IE version, if it ever worked at all).
You can handle events using:
htmlElementObj.onclick = function(e) {
//e->event object
};
However Internet Explorer doesn't pass event object to handler. Instead you can use window.event object which is being updated immediately after the event was fired.
htmlElementObj.onclick = function(e) {
e = e || window.event;
}
In Firefox and Chrome my code works fine but in IE the event does not get removed.
dojo.connect(d, "onmouseout", function(evt) {
//remove event
});
I've tried:
document.removeEventListener("keydown", keyHandler);
dojo.disonnect(document, "keydown", keyHandler);
document.detachEvent("keydown", keyHandler);
But nothing seems to work. keyHandler is the function which I don't want to execute on keydown when the mouse is out of the canvas stored in variable d.
Managed to get it working with this command: document.onkeydown = null;
Check if you are using the disconnect function properly (and check the spelling/syntax as well). The documentation says:
disconnect() accepts a specially-crafted parameter as it’s only
argument which, coincidentally, is the return value from dojo.connect.
...while you supply 3 parameters to it, the handler being the last one.
As a side note, I am not quite sure about what happens inside Dojo (though it probably implements a polyfill, so you don't have to use native functions if you use Dojo), but IE's attachEvent and detachEvent accepts event names prefixed with 'on', e.g. onmouseout, onkeydown (see the MSDN article).
Also, note the difference in event names. Dojo seems to use IE's syntax with on prefix, while the standard DOM implementation omits it. So, you may want to check if you are binding and unbinding the same event (e.g. if you bind to onkeydown, then you should unbind onkeydown and not keydown).
I'm novice with both JS and jQuery, and I'm a little bit confused about what situations would require you to pass event as an argument into the function, and what situations you would not need to.
For example:
$(document).ready(function() {
$('#foo').click(function() {
// Do something
});
});
versus
$(document).ready(function() {
$('#foo').click(function(event) {
// Do something
});
});
The event argument has a few uses. You only need to specify it as an argument to your handler if you're actually going to make use of it -- JavaScript handles variable numbers of arguments without complaint.
The most common use you'll see is to prevent the default behavior of the action that triggered the event. So:
$('a.fake').click(function(e) {
e.preventDefault();
alert("This is a fake link!");
});
...would stop any links with the class fake from actually going to their href when clicked. Likewise, you can cancel form submissions with it, e.g. in validation methods. This is like return false, but rather more reliable.
jQuery's event object is actually a cross-browser version of the standard event argument provided in everything but IE. It's essentially a shortcut, that lets you use only one code path instead of having to check what browser you're using in every event handler.
(If you read non-jQuery code you'll see a lot of the following, which is done to work around IE's deficiency.
function(e) {
e = e || window.event; // For IE
It's a pain, and libraries make it so much easier to deal with.)
There's a full accounting of its properties in the jQuery docs. Essentially, include it if you see anything you need there, and don't worry otherwise. I like to include it always, just so I never have to remember to add it in later if I decide that it's needed after all.
You only need the event if you're going to use it in the body of the handler.
Since you are using jQuery, you only put event as an argument if you need to use the event in the handler, such as if you need the key that was pressed on a keypress event.
In JS, without jQuery or Prototype etc., you need to pass the event as a parameter for standards compliant browsers like Firefox, but the event is not passed as an argument in IE. IE actually maintains a global variable window.event. So in your handler (sans library) you need to check if the argument is undefined; if so, grab the global variable.
function eventHandler(evt) {
var theEvent = evt || window.event;
//use the event
}
But a library like jQuery takes care of that for you.
I honestly don't recommend using a library until you have learned the language. But if this is for a job, the by all means use the library, but learn the details of JS on your own, so you can better appreciate it.