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
});
Related
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.
In a book, the code for handling mouseDown event is like this:
mousedownhandler: function (ev) {
mouse.down = true;
mouse.downX = mouse.x;
mouse.downY = mouse.y;
ev.originalEvent.preventDefault();
}
So my question is why use ev.originalEvent.preventDefault(); but not ev.preventDefault(); or return false; in this case (HTML5 game)?
jQuery alters the event methods / data in the returned event.
Using event.originalEvent, you're able to retrieve this back.
For example jQuery strips the dataTransfer api for dragged items, using the originalEvent you can use it again.
docs: "jQuery normalizes the following properties for cross-browser consistency ... To access event properties not listed above, use the event.originalEvent object"
In the proposed case it's used to access the preventDefault method (which stops the default action) as it's not included in the jQuery event.
See the definition of preventDefault in jQuery 3.1.1:
jQuery.Event.prototype = {
// ...
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
// ...
};
So basically it will just call native preventDefault. If you are using jQuery I would use its method, it will also update isDefaultPrevented which might be useful if you want to check it (but you could also use native .originalEvent.defaultPrevented).
If you don't care about isDefaultPrevented and know the event has not been simulated by jQuery, then calling native preventDefault might be few milliseconds faster. That's the only potential advantage I can think of, but this definitely won't be a bottleneck.
Returning false in a jQuery event listener is like using both preventDefault and stopPropagation.
I use to know if the event was actually triggered by a physical mouse click. This is useful for avoiding the use of captchas on submit forms.
Here the case: I want to call the event with apply method, since it's look the one with the best compatibility with any browser.
my_object["onchange"].apply(my_object, event)
So, the event parameter doesn't exist when you define online, example :
<select id="my_select" onchange="my_onchange(event);" >
The event object is create by the engine, but what if I call it with apply?
If I try my_object["onchange"].apply(my_object) the event parameter is not build. Normal because it's call like a function.
So any idea to do build the event?
update
I have try
var event = new Event("onchange", {target:my_object});
It's look like target still readonly even with constructor.
So my workaround is
var event = document.createEvent("HTMLEvents");
event.initEvent("change", false, true);
my_object.dispatchEvent(event);
it's look like it's compatible with all browser and generate the good event parameter.
Thanks
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.
I want to check if an event is available or not before binding a function to it.
The problem is that Google Chrome support the event "loadedmetadata" in the Video element while FireFox don't.
I did the following
$('video').bind('loadedmetadata', videoloaded);
videoloaded();
It worked well in Firefox but when I tried in Chrome, the function was executed twice (which is logical). I want to check if loadedmetadata event handler exists or not to run the function only one time in each browser.
If such possibility doesn't exist, any intelligent work around for this?
Check the $video.data("events") if this object contains your event, since you are using .bind all events of this element will be stored in this object.
var $video = $("#video");
var $ve = $video.data("events");
// checking if a `loadedmetadata` object exists in `data("events")`
if ($ve != null && typeof($ve.loadedmetadata) !== undefined)
{
// has loadedmetadata event
}
Full working example on jsFiddle