onreadystatechange event function [duplicate] - javascript

I am using the following code and it works perfectly fine in Chrome.
function dayBind(xyzValue) {
if(event.type == 'click')
alert('Mouse Clicked')
}
Note that there was no 'event' variable passed to the function but still it was available for me in case of chrome. But when I use Firefox I get 'event' undefined.
I tried using the following workarounds:
var e=arguments[0] || event;
also:
var e=window.event || event;
But none of them worked for me. Is there any 'event' equivalent in Firefox?

Because IE and Chrome put the event in the global object window, so you can get it. In firefox, you need to let the first parameter be the event.
function dayBind(event, xyzValue) {
var e=event || window.event;
if(event.type == 'click')
alert('Mouse Clicked')
}

If you're setting up the handler with an "onclick" attribute or something (which, since you tagged the question "jQuery", you really should consider not doing), you have to explicitly pass it:
<button type=button onclick='whatever(event)'>Click Me</button>

If you need it to work cross browser, simply use the arguments object:
function dayBind()
{
var e=arguments[0];
if(!!e && e.type === 'click')
{
alert('Mouse Clicked')
}
}
References
Overview of Events and Handlers
DOM Event Handlers
eventTarget.addEventListener

I am working in a plugin's callback function. I cannot call it myself.
One simple question to your suggestion: when you write: onclick="whatever(event)" you are writing javascript in the value of onclick attribute, right?
Why can't you make the same function call inside some other function like this:
function foo(){ whatever(event); // this is also javascript }
// But this doesn't work for me in FireFox 10.0.2
The code in the "onclick" attribute should be thought of as part of a function that the browser creates for you. That function automatically has the "event" parameter available. Writing the attribute as I did in the answer cause that parameter to be passed on the your other function.
Really, you should read about the jQuery API and use that to bind event handlers instead of using "onclick" and other similar attributes.

Related

Event Object Storage

I am new to scripting and for a function(e) e is event object can anyone please update me for my few concerns
it will created when a event is triggered so when it will removed . so every event an object is created?
where these objects get stored?
That is just an event handler variable.
Doesn't matter if its e or event
It really doesn't matter whether you use e or event or anyother word for this.
function (e):
When you use this:
function (e) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/1/ (fiddle for function (e))
function (event):
This is just a name you're giving to the current event, you can change that to
function (event) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/2/ (fiddle for function (event))
function (something):
Or even to this:
function (something) {
// code..
}
http://jsfiddle.net/afzaal_ahmad_zeeshan/kKb4H/3/ (fiddle for function (something))
Their usage
You use these, to get the methods for the current object; such as event.keyCode, to get the keyCode which is used in a function where keyboard is used.
Where they are present
They are included in JavaScript and you don't need any more dependendies for it to work and you don't need any more coding work for it.
What a function looks like
They aren't removed, once a function is executed, it has an event parameter or what you can call argument. as:
function (event) { // event is the argument
if(event.keyCode == 13) { // using its method of keycode
/* and comparing its value to 13
* 13 is for enter
* you get a bool value; either true of false and do the coding */
}
}
Simple answer
From the fiddles you will get to the result that e doesnot require to be e only. It can be anything that you want to be written in the code. Something is no method in JavaScript, but usage of it at the first argument made it an event handler, and it got the methods of event.
They are not stored in browser, they are a part of every browser! When you say a browser supports this feature it means it includes all the files that are required to run a code.

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.

using jquery to access event values?

When using for events for internet explorer we are currently using statements like this to access or change values:
window.event.cancelBubble = true;
clickX = window.event.screenX;
I was wondering how to do this cross browser or using JQuery?
When you provide a callback to a jquery binding function, it always take as first parameter a event that you should use, even on IE.
Don't use window.event if you're using jQuery.
Note that this is a jQuery wrapped event. For some uses you may need the originalEvent property of the event you get. Here's how you can get both in a callback :
​$('#A').click(function(e){
console.log(e); // jquery event
console.log(e.originalEvent); // native event
});​

Adding a javascript function call to an event (such as 'window.resize') instead of overwriting what is already there

Is there a way to tell the browser to run an addtional java script function on an event such as 'window.resize' instead of overwriting what is already there?
Using jquery's
$(window).resize(<something>);
Seems to replace what is already there. Is there a way to tell it to do something in addition?
Is this a poor design / wrong way to do it?
I wouldn't think that jQuery would break what's there, but you could wrap the functions in a single function:
// if a function already exists...
if( window.onresize ) {
var prev_func = window.onresize; // cache the old function
window.onresize = function( event ) { // new function for resize
prev_func.call( window, event ); // call the old one, setting the
// context (for "strict mode") and
// passing on the event object
// call your code or function
};
}
EDIT: Fixed it to use onresize instead of resize.
EDIT2: Missed one! Fixed.
If you're using jQuery to bind all event handlers, then you're not breaking anything. jQuery supports multiple handlers for same event.
But if other code (not using jQuery) binds to the event, then you'll overwrite handler with your statement. The solution will be: always use jQuery for event binding or try to save old handler (see patrick dw's answer).
See element.addEventListener (element.attachEvent in IE 8 and under):
// Standards
if (window.addEventListener){
window.addEventListener("resize", callOnResize, false);
// IE 8 and under
} else if (window.attachEvent){
window.attachEvent('resize', callOnResize);
}
function callOnResize() {
console.log("resized");
}
Keep in mind this is pure JavaScript—jQuery (and pretty much any big JS library) has a method to handle creating standards and IE handlers without you needing to write each. Still, it's good to know what's happening behind the scenes.
jQuery and all other frameworks supporting custom events attach a function to the event of the elem (or observe it). That function then triggers all functions that have been bound (using bind) for a specific event type.
domelement.addEventListener does not override an other function and your function added can't be removed by other (bad) javascript, except when it would know the exact footprint of your function.

JavaScript event handlers -why no alert?

I'm a newbie at JavaScript trying to learn event handlers. Looking at this fiddle http://jsfiddle.net/mjmitche/uV4kv/ can anyone tell me why the pop up is not appearing when the link is clicked?
I've also copied the code below
click me
function addEventHandler(oNode, sEvt, fFunc, bCaptures){
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+sEvt, fFunc);
else
oNode.addEventListener(sEvt,fFunc,bCaptures);
}
function onLinkClicked(e) {
alert("you clicked the link");
}
function setUpClickHandler(){
addEventHanlder(document.getElementById('clickLink'), "click", onLinkClicked, false);
}
addEventHandler(window,"load",setUpClickHandler,false);
There are basically three problems:
You have some typos, e.g. "Hanlder" instead of "Handler" and "Sevt" instead of "sEvt".
The code is already run after page load, so the event handler you add to window will never be called. Change in jsFiddle from onLoad to no wrap (head).
You "IE detection" does not work. I get this error in Chrome:
Uncaught TypeError: Object http://fiddle.jshell.net/_display/# has no method 'attachEvent'.
Better would be to test whether the function window.attachEvent exists. I also think that window.event is only available when an event is raised.
If this is corrected, your code will run (DEMO).
Further notes:
Testing which method is supported (i.e. attachEvent or addEventListener) on every call of your function is unnecessary. It won't change during the life of the page. Better is to test only once at the beginning. Example:
var addEventHandler = (function() {
if(window.attachEvent) {
return function(oNode, sEvt, fFunc) {
oNode.attachEvent("on"+sEvt, fFunc);
};
}
else {
return function(oNode, sEvt, fFunc, bCaptures) {
oNode.addEventListener(sEvt,fFunc,bCaptures);
};
}
}());
This assigns a function the supported function to addEventHandler.
A couple of problems:
You have a recurring typo, "Hanlder" instead of "Handler". There are at least two, one where you do your setUpClickHanlder (sic) function, and one within it (addEventHanlder).
Also, you have "Sevt" where you mean "sEvt". (JavaScript is case sensitive.)
Let tools help you. Use a browser that gives you a console showing errors. Use a debugger for single-stepping through code, looking at variable values at runtime with inspectors, etc.
Your addEventHandler needs adustment:
function addEventHandler(oNode, sEvt, fFunc, bCaptures) {
oNode.attachEvent ? oNode.attachEvent ("on" + sEvt, fFunc) :
oNode.addEventListener (sEvt, fFunc, bCaptures);
}
It is in event handlers themselves that you need to check for window.event

Categories

Resources