'event' equivalent in Firefox - 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

How to check if onresize method is set?

Can I check if a onresize method was set?
I've previously used:
$(window).resize(function() { /* ... */ });
Due a unknown bug in another library, onresize is not called anymore. After executing above line it works perfectly again. The method is invoked once. If I execute the line in the Firebug console again, the method is invoked twice.
I would like to write a workaround, which sets onresize as soon as it's "reseted".
I'm looking for something like that: (undefined or null)
if (window.onresize == undefined) { /* ... */ }
The external library/framework is Richfaces 4 (Extended Data Table). As soon as I sort a column, some of the onresize function handler were gone.
Before:
$._data(window,'events').resize
// result on the Chrome console:
[Object, Object, Object, Object]
After using sorting:
$._data(window,'events').resize
// result on the Chrome console:
[Object]
I'm looking for a way to write a workaround.
JIRA Issue
https://issues.jboss.org/browse/RF-13117 (fixed with future release 4.3.4)
You could use $._data() which is not a method publicly supported:
$(window).on('load',function() {
if(!$._data(window,'events').resize)
alert('none resize bound');
});
In older jquery version it was: $.data()
what i used in my project was
$(window).unbind('resize').bind('resize',function(){
//code here
});
it will remove all the previously bind (registered) handlers for resize event and register this new function as the handler.
this approach is useful only when you want to attach a single event handler.
Thanks for all answers and comments. As suggested I went to the source of the problem and wrote for that a workaround including opening an issue.
window.RichFaces.ui.ExtendedDataTable.prototype.deActivateResizeListener = function() {
if (this.resizeEventName != undefined) {
$(window).off(this.resizeEventName);
}
};
I accepted roasted answer since it really helped to find a workaround and his answer answered my question if there is a way to find out if a event handler is attached.

'attacheventlistener' and 'onclick' prototype

Maybe there are serval sub-questions for my problem:
Is there a general solution to get events binded to an element?(Without jquery or others javascript librarys).
I found $(element).data('events') can't get event registered with <element onclick="some_functions()">. How can we get it?
My goal is to insert an event before native event (registered by the programmer of html page). I found two solutions.
Using jQuery as described here
modify HTMLElement.prototype.addeventlister as described here
However, I find both these methods can't solve the situation like that
<element onclick="some_functions()">
You can access (and overwrite) that event handler via the onclick property. If you have a
<span id="elem" onclick="some_functions()">
then document.getElementById("elem").onclick will yield the anonymous function
function (event) {
some_functions()
}
To intercept it, you can use something like
var fn = elem.onclick;
elem.onclick = function() {
console.log("before");
var res = fn.apply(this, arguments);
console.log("after");
return res;
};
Disclaimer: This might not in older browsers, I don't know how the inventors (Netscape, IE) of inline attribute event handlers and traditional event registration handled these. They might as well have done something like eval(elem.getAttribute("onclick")), in any case you can access the handler code (as a string) like that.

Get value of current event handler using jQuery

I can set the onclick handler using jQuery by calling
$('#id').click(function(){
console.log('click!');
});
Also using jQuery, how can I get a reference to the function which is currently handling the click() event?
The reason is that I have another object and want to set its click handler to the same one as #id.
Update
Thank you for all the suggestions. The problem is that I do not know which function is currently handling the clicks. Keeping track of it would add state to an already complicated template-editing system.
jQuery's .click(function) method adds the function to a queue that is executed on the click event~
So actually pulling out a reference to the given function would probably be hairy-er than you expect.
As noted by others, it would be better to pass in a reference to the function; and then you already have the reference you need.
var clicky = function () { /* do stuff */ };
$('#id').click(clicky);
// Do other stuff with clicky
Update
If you really really need to get it out, try this:
jQuery._data(document.getElementById('id')).events.click[0].handler
Depending on your version of jQuery that may or may not work~ Try playing around with
jQuery._data(document.getElementById('id'))
and see what you get.
Got the idea from this section of the source:
https://github.com/jquery/jquery/blob/master/src/event.js#LC36
if you dont know the name of the function you can use
args.callee
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
function clickHandle(e){
if($(e.target) == $('#id')) {
$(newTarget).bind('click', clickHandle);
}
}
$('#id').bind('click',clickHandle);
I think this would be the most symantic way of going about it

What's a good example for browser-specific code necessary when not using e.g. jQuery?

I'm looking for a good example where a framework/lib like jQuery removes the need for browser-specific code. Please note that I'm not looking for an example where jQuery makes things just easier or nice but specifically something where the same code wouldn't work for all common browsers.
As it'll be used for university stuff and just meant to be an example a very simple thing would be great (otherwise I'd probably use e.which vs e.keyCode)
Event handling is a good example, as it is so important for today's web applications.
element.addEventListener does not work in IE8 and below. These things are different in IE:
You have to use element.attachEvent and 'on<event>':
element.addEventListener('click', handler, false); // W3C
// vs.
element.attachEvent('onclick', handler); // IE
As IE's event model is a bit different, it does not support listing to events in the capture phase:
element.addEventListener('click', handler, true); // W3C
// vs
// not possible :( // IE
IE does not pass the event to the handler (it is available in via window.event):
function handler(event) {
event; // W3C
// vs
window.event; // IE
}
Inside the event handler, this does not refer to element the handler is bound to, but to window:
function handler() {
alert(window === this); // true // IE
}
Notice: This is only the case for event handlers bound via attachEvent. In inline event handlers and the ones assigned to the onclick property, this refers to the element.
Different properties of the event object (e.g. no event.stopPropagation):
event.stopPropgation(); // W3C
// vs.
event.cancelBubble = true; // IE
Except for the capturing, all these things can be dealt with by creating an appropriate wrapper function (what jQuery is basically doing). How such a method could look like can be found in my answer to this question.
You can find more information about these differences on quirksmode.org:
Advanced event registration models
Event properties
Event order
The this keyword
You can talk about jQuery's normalised event object, and in particular how it simplifies getting the event's target/sourceElement, eliminating the need for code like this:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
(From http://www.quirksmode.org/js/events_properties.html#target)
Handling AJAX requests, here's a sample function you'd need to get a XML http request object if you were supporting multiple browsers without using jQuery -
function getXHR () {
var request = null;
if (window.XMLHttpRequest) {
try {
request = new XMLHttpRequest();
} catch(e) {
request = null;
}
// Now try the ActiveX (IE) version
} else if (window.ActiveXObject) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
// Try the older ActiveX object for older versions of IE
} catch(e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
request = null;
}
}
}
return request;
};
although all the examples stated above all are good examples but they are not part of everyones daily routine while working with JS.
The biggest advantage that I can see is how simple it is to use the selectors without me worrying about remembering the n of syntaxes and which browsers a particular method works and where not.
Yes I am talking about the native dom selectors like
getElementByid(id) => $("#id")
getElementByClass(class) => $(".class")
getElementByTagName("tagname") => $("tagName")
and also the fact that I dont need to worry about how many elements are being returned as part of the result set I can use some other api on the returned object instantly.
Also some of the dom manipulation code is something that irritates the hell out of me using native queries..
especially when i need to add new script tags into the dom you need to set the type etc. before inserting it into the dom with jquery all I need to do is use the html() method. and one more plus of the html() method is it will take care of which code implementation it should use that is whether it is possible to use innherHTML for better performance or if its a readonly control like some of those in IE append it to those etc..
then there are other things like others have noted how easy it is to deal with XHttp requests especially cross domain requests using jsonp with the SAME ORIGIN POLICY that is enforced by browsers..
Event handling being the other tricky thing with so many minor issues that you run into with every control.. just look at jquerys source code once and you will understand what I am talking of.

How to programmatically generate a window.event using Javascript?

I am currently unit testing some javascript, where it handles an event raised by clicking on a certain item in the window. Below is a snipet of the code:
function someFunction()
{
var evt = window.event ? window.event : event;
if (evt == null) { return; }
var nodeElement = evt.srcElement;
if (nodeElement == null) { return; }
.
.
.
}
My current approach is to try to create a custom event in my test file which will populate window.event so I can at least get to test the nodeElement == null part. But I am having difficulties doing so (being not from a Javascript backgound). How do I actually create a custom event (in IE)? I'm currently doing unit testing using JsTestDriver so no html file is used. I do not mind using jQuery or just plain Javascript solution.
Thanks.
I would definitely use jQuery (or some other framework). It will make your life easier. I am sure every browser will have a different way of triggering the event.
http://docs.jquery.com/Events
With jQuery you just do something like
$(window).trigger("eventname")
I currently wrote a blog post series about custom events in jQuery. You can use .trigger and .bind and it is really powerful.
As alex has pointed out in his comment, you can use jQuery to create events with
$("css selector here").jQueryEventFunction(functionToCall);
So, following your example, if you want to invoke someFunction when a label is clicked you can do:
$("#label-id").click(someFunction);
Now, if you want to simulate clicking it
$("#label-id").click();
And that will do it.
EDIT For the window event you can use
$(window).click(someFunction);
That will bind any click done in the window to someFunction. And if you call $(window).click(); a click event will be simulated, calling someFunction.

Categories