I have a tiny function I use to only allow numeric input. It works great in IE, but I cannot get it to work in FireFox or Chrome. I have this js file loaded in my script tag of my HTML page.
var numberOnly = function(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
}
};
var wireElemToEvent = function(elemId, event, func){
var elem = document.getElementById(elemId);
if (typeof window.event !== 'undefined') {
elem.attachEvent("on" + event, func);
} else {
elem.addEventListener(event, func, true);
}
};
var wireEvents = function(){
wireElemToEvent("tbxQuantity", "keypress", numberOnly);
wireElemToEvent("tbxPhone", "keypress", numberOnly);
wireElemToEvent("tbxZip", "keypress", numberOnly);
};
window.onload = wireEvents;
Chrome tells me
file:///C:/Documents%20and%20Settings/xxx/Desktop/numbersonly/res/js/numbersonly.js:17Uncaught TypeError: Object #<an HTMLInputElement> has no method 'attachEvent'
Any idea what I am doing wrong?
In wireElemToEvent You may want to check that elem is not null after you initialize it. Also, it would be better to check the existence of elem.attachEvent and elem.addEventListener rather than whether window.event is defined.
Here is the function I use to attach events cross browser:
function eventListen( t, fn, o ) {
o = o || window;
var e = t+fn;
if ( o.attachEvent ) {
o['e'+e] = fn;
o[e] = function(){
o['e'+e]( window.event );
};
o.attachEvent( 'on'+t, o[e] );
}else{
o.addEventListener( t, fn, false );
}
}
And to use it:
eventListen('message', function(e){
var msg = JSON.parse(e.data);
...
});
I've had the same problem and, because I am a novice, was looking around for a day for a solution.
Apparently (typeof window.event !== 'undefined') doesn't stop Safari/Chrome from getting in that if statement. So it actually initializes the attachEvent and doesn't know what to do with it.
Solution:
var wireElemToEvent = function(elemId, event, func){
var elem = document.getElementById(elemId);
if (elem.attachEvent) {
elem.attachEvent("on" + event, func);
}
else { // if (elem.addEventListener) interchangeably
elem.addEventListener(event, func, true);
}
};
One good way to make cross-browser scripting easier is to use jQuery. Plus, there's no reason to reinvent the wheel. Why not try this jQuery plugin: jQuery ยป numeric
Related
What is the equivalent to the Element Object in Internet Explorer 9?
if (!Element.prototype.addEventListener) {
Element.prototype.addEventListener = function() { .. }
}
How does it works in Internet Explorer?
If there's a function equal to addEventListener and I don't know, explain please.
Any help would be appreciated. Feel free to suggest a completely different way of solving the problem.
addEventListener is the proper DOM method to use for attaching event handlers.
Internet Explorer (up to version 8) used an alternate attachEvent method.
Internet Explorer 9 supports the proper addEventListener method.
The following should be an attempt to write a cross-browser addEvent function.
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
}
else { // No much to do
elem["on"+evnt] = func;
}
}
John Resig, author of jQuery, submitted his version of cross-browser implementation of addEvent and removeEvent to circumvent compatibility issues with IE's improper or non-existent addEventListener.
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
Source: http://ejohn.org/projects/flexible-javascript-events/
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.
You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).
You can also use a framework like jQuery to abstract the event handling altogether.
$("#someelementid").bind("click", function (event) {
// etc... $(this) is whetver caused the event
});
Here's something for those who like beautiful code.
function addEventListener(obj,evt,func){
if ('addEventListener' in window){
obj.addEventListener(evt,func, false);
} else if ('attachEvent' in window){//IE
obj.attachEvent('on'+evt,func);
}
}
Shamelessly stolen from Iframe-Resizer.
addEventListener is supported from version 9 onwards; for older versions use the somewhat similar attachEvent function.
EDIT
I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects:
https://github.com/antcolag/iEventListener/blob/master/iEventListener.js
OLD ANSWER
this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help
(function (w,d) { //
var
nc = "", nu = "", nr = "", t,
a = "addEventListener",
n = a in w,
c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
u = n?(nu = "attach", "add"):(nu = "add","attach"),
r = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
*/
function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt ))}}
w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]
})(window, document)
I would use these polyfill https://github.com/WebReflection/ie8
<!--[if IE 8]><script
src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->
I have a shimmed and polyfilled version of angularjs 1.3 working perfectly on ie8. Unfortunately when mootools is included on the page there are quite a few conflicts. I have managed to get a handle on all but one with the following which adds add / remove EventListener and dispatchEvent to Window.prototype, HTMLDocument.prototype and Element.prototype. It checks to see if mootools is loaded and if so it adds them differently.
!window.addEventListener && (function (WindowPrototype, DocumentPrototype, ElementPrototype, addEventListener, removeEventListener, dispatchEvent, registry) {
var addEventListenerFn = function(type, listener) {
var target = this;
registry.unshift([target, type, listener,
function (event) {
event.currentTarget = target;
event.preventDefault = function () {
event.returnValue = false;
};
event.stopPropagation = function () {
event.cancelBubble = true;
};
event.target = event.srcElement || target;
listener.call(target, event);
}]);
// http://msdn.microsoft.com/en-us/library/ie/hh180173%28v=vs.85%29.aspx
if (type === 'load' && this.tagName && this.tagName === 'SCRIPT') {
var reg = registry[0][3];
this.onreadystatechange = function (event) {
if (this.readyState === "loaded" || this.readyState === "complete") {
reg.call(this, {
type: "load"
});
}
}
} else {
this.attachEvent('on' + type, registry[0][3]);
}
};
var removeEventListenerFn = function(type, listener) {
for (var index = 0, register; register = registry[index]; ++index) {
if (register[0] == this && register[1] == type && register[2] == listener) {
if (type === 'load' && this.tagName && this.tagName === 'SCRIPT') {
this.onreadystatechange = null;
}
return this.detachEvent('on' + type, registry.splice(index, 1)[0][3]);
}
}
};
var dispatchEventFn = function(eventObject) {
return this.fireEvent('on' + eventObject.type, eventObject);
};
if(Element.prototype.$constructor && typeof Element.prototype.$constructor === 'function') {
Element.implement(addEventListener, addEventListenerFn);
Element.implement(removeEventListener, removeEventListenerFn);
Element.implement(dispatchEvent, dispatchEventFn);
Window.implement(addEventListener, addEventListenerFn);
Window.implement(removeEventListener, removeEventListenerFn);
Window.implement(dispatchEvent, dispatchEventFn);
} else {
WindowPrototype[addEventListener] = ElementPrototype[addEventListener] = addEventListenerFn;
WindowPrototype[removeEventListener] = ElementPrototype[removeEventListener] = removeEventListenerFn;
WindowPrototype[dispatchEvent] = ElementPrototype[dispatchEvent] = dispatchEventFn;
}
DocumentPrototype[addEventListener] = addEventListenerFn;
DocumentPrototype[removeEventListener] = removeEventListenerFn;
DocumentPrototype[dispatchEvent] = dispatchEventFn;
})(Window.prototype, HTMLDocument.prototype, Element.prototype, 'addEventListener', 'removeEventListener', 'dispatchEvent', []);
This has resolved all my errors bar one. When this function is called in Angular, when mootools is on the page, and element is a form addEventListener is undefined.
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
}
specifically this function is called from angulars formDirective like so
addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
Any ideas why the form element still dosn't have the addEventListener function available?
Extending native type via Element.prototype in IE8 is considered very unreliable as the prototype is only partially exposed and certain things are not inheriting from it / misbehave.
http://perfectionkills.com/whats-wrong-with-extending-the-dom/
What MooTools does in this case is rather than work around the quirks of all edgecases that don't adhere to the correct proto chain (and because of IE6/7 before that) is to COPY the Element prototypes on the objects of the DOM nodes as you pass it through the $ selector.
This is not ideal, because.
var foo = document.id('foo');
// all known methods from Element.prototype are copied on foo, which now hasOwnProperty for them
Element.prototype.bar = function(){};
foo.bar(); // no own property bar, going up the chain may fail dependent on nodeType
Anyway, that aside - you can fix your particular problem by copying your methods from the Element.prototype to the special HTMLFormElement.prototype - any any other elements constructors you may find to differ.
It's not scalable, you may then get an error in say HTMLInputElement and so forth, where do you draw the line?
I need to found other way how to use javascript function.
var b = ce("input"); // Here I create element.
b.setAttribute("name", "g4");
b.value = "Centimetrais(pvz:187.5)";
b.onfocus = function() { remv(this); };
b.onchange = function() { abs(this); };
b.onkeypress = function() { on(event); }; // I need to change this place becose then I pass "event" argument function doesn't work.
ac(1, "", b); // Here I appendChild element in form.
Here is the function:
function on(evt) {
var theEvent = evt|| window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /^[0-9.,]+$/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
In IE and chrome it work but in mozilla doesn't. Any alternative how to fix it for firefox?
Also at this path other function working in mozilla if pass other argument like "car","dog",this. For example:
firstFunction();
function firstFunction() {
var b = ce("input"); // Here I create element.
b.onkeypress = function() { on("hi!"); };
ac(1, "", b); // Here I appendChild element in form.
}
function on(evt) {
alert(evt);
}
If I understand your question correctly, the problem is that you're not accepting the event argument in the main handler. E.g., in your first example:
b.onkeypress = function() { on(event); };
it should be
b.onkeypress = function(e) { on(e || window.event); };
// Changes here --------^ and --^^^^^^^^^^^^
You're doing that in on, but in on, it's already too late, you've lost the argument provided to the onXYZ function.
The reason your code works in Chrome and IE is that IE uses a global event object instead of (or in modern versions, in addition to) the one it actually passes into the handler, and Chrome replicates that behavior for maximum compatibility with websites that expect that. Firefox does not.
I've been putting together a lightweight event utility for cross-browser event handling, but have come across a rather high hurdle I can't quite jump over. It's concerning the srcElement property in IE9, which just isn't working for me!
Currently, my utility looks something like this (the srcElement is the 3rd code block):
var bonsallNS = new Object();
bonsallNS.events = {
addEvent: function (node, type, func) {
if (typeof attachEvent != "undefined") {
node.attachEvent("on" + type, func);
} else {
node.addEventListener(type, func, false);
}
},
removeEvent: function (node, type, func) {
if (typeof detachEvent != "undefined") {
node.detachEvent("on" + type, func);
} else {
node.removeEventListener(type, func, false);
}
},
target: function (e) {
if (typeof srcElement != "undefined") {
return window.event.srcElement;
} else {
return e.target;
}
},
preventD: function (e) {
if (typeof srcElement != "undefined") {
window.event.returnValue = false;
} else {
e.preventDefault();
}
}
}
Now, using the following test script below works fine in Chrome and Firefox, but returns the evtTarget to be undefined in IE when I try to alert it. I have NO idea why, so any help would be greatly appreciated! See below code:
var gClick = document.getElementById("clickme");
var gCount = 0;
function mssg(e){
var evtTarget = bonsallNS.events.target(e);
alert("it worked, target: " + evtTarget);
gCount++
if (gCount > 2){
bonsallNS.events.removeEvent(gClick, "click", mssg);
}
}
function setUp(){
bonsallNS.events.addEvent(gClick, "click", mssg);
}
bonsallNS.events.addEvent(window, "load", setUp);
Like I say, everything else works except for the event source in IE!!
The variable srcElement will always be undefined unless it's defined in a higher scope. But it will never refer to event.srcElement.
You can solve this problem in two ways: Either check whether e or e.srcElement are not defined, or whether window.event and window.event.srcElement are defined.
if (typeof e === "undefined" || typeof e.srcElement === "undefined") {
// or
if (typeof window.event !== "undefined" &&
typeof window.event.srcElement !== "undefined") {
You can also shorten the whole function to:
target: function (e) {
e = e || window.event;
return e.target || e.srcElement;
}
What is the equivalent to the Element Object in Internet Explorer 9?
if (!Element.prototype.addEventListener) {
Element.prototype.addEventListener = function() { .. }
}
How does it works in Internet Explorer?
If there's a function equal to addEventListener and I don't know, explain please.
Any help would be appreciated. Feel free to suggest a completely different way of solving the problem.
addEventListener is the proper DOM method to use for attaching event handlers.
Internet Explorer (up to version 8) used an alternate attachEvent method.
Internet Explorer 9 supports the proper addEventListener method.
The following should be an attempt to write a cross-browser addEvent function.
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
}
else { // No much to do
elem["on"+evnt] = func;
}
}
John Resig, author of jQuery, submitted his version of cross-browser implementation of addEvent and removeEvent to circumvent compatibility issues with IE's improper or non-existent addEventListener.
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
if ( obj.detachEvent ) {
obj.detachEvent( 'on'+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );
}
Source: http://ejohn.org/projects/flexible-javascript-events/
I'm using this solution and works in IE8 or greater.
if (typeof Element.prototype.addEventListener === 'undefined') {
Element.prototype.addEventListener = function (e, callback) {
e = 'on' + e;
return this.attachEvent(e, callback);
};
}
And then:
<button class="click-me">Say Hello</button>
<script>
document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
console.log('Hello');
});
</script>
This will work both IE8 and Chrome, Firefox, etc.
As Delan said, you want to use a combination of addEventListener for newer versions, and attachEvent for older ones.
You'll find more information about event listeners on MDN. (Note there are some caveats with the value of 'this' in your listener).
You can also use a framework like jQuery to abstract the event handling altogether.
$("#someelementid").bind("click", function (event) {
// etc... $(this) is whetver caused the event
});
Here's something for those who like beautiful code.
function addEventListener(obj,evt,func){
if ('addEventListener' in window){
obj.addEventListener(evt,func, false);
} else if ('attachEvent' in window){//IE
obj.attachEvent('on'+evt,func);
}
}
Shamelessly stolen from Iframe-Resizer.
addEventListener is supported from version 9 onwards; for older versions use the somewhat similar attachEvent function.
EDIT
I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects:
https://github.com/antcolag/iEventListener/blob/master/iEventListener.js
OLD ANSWER
this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help
(function (w,d) { //
var
nc = "", nu = "", nr = "", t,
a = "addEventListener",
n = a in w,
c = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
u = n?(nu = "attach", "add"):(nu = "add","attach"),
r = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
* the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
*/
function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt ))}}
w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]
})(window, document)
I would use these polyfill https://github.com/WebReflection/ie8
<!--[if IE 8]><script
src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->