My code works fine in FF/Chrome/Everything except IE(failed in both 7/8, didn't bother going furthur down). Due to restrictions, I cannot use jQuery and am hard-coding the Javascript. The issue is with IE, I am getting "preventDefault is null or not an object". Hoping one of you has the answer, and here's relevant code:
AddEvent Method:
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 );
};
Event handler throwing error:
function mousedown(e){
if(e.preventDefault){
e.preventDefault();
} else {
e.returnValue = false;
e.cancelBubble=true;
}
//Processing
};
Also DOCTYPE and charset are both set on the calling HTML page. Any ideas would be appreciated. The error is thrown in the if statement for the mousedown method.
EDIT:
Due to the fact that grabbing window.event did "fix" the main issue, I discovered the problem was a different section of code. Basically I am adding a element ontop of a pre-placed element, and then registering mousedown/mousemove events to that div. When firing the event on the <div>, THAT'S where the error is thrown.
Could this be something due to the fact that I have events registered to 2
rect = document.createElement('div');
rect.className='square';
rect.id='chooser_rectangle';
rect.style.left=initx+'px';
rect.style.top=inity+'px';
addEvent(rect,"mousemove",mousemove);
addEvent(rect,"mousedown",mousedown);
In IE the event object is not passed as the first argument to an event handler. Instead it is a global variable:
function mousedown(e){
var evt = e || window.event; // IE compatibility
if(evt.preventDefault){
evt.preventDefault();
}else{
evt.returnValue = false;
evt.cancelBubble=true;
}
//Processing
};
IE has a different event model to other browsers (even IE8). In IE you would call this to do the same thing:
event.returnValue = false;
You need to determine what the browser supports and call the correct method. So first check if event.returnValue is set, if so then call it, otherwise call preventDefault().
Related
The book that I am learning JS from has code like below :
function check(e) {
if (!e){
e = window.event; // for IE
}
var target = e.target || e.srcTarget;
if (**e.preventDefault**){
e.preventDefault() ;
}
target.returnValue = false;
}
var el = document.getElementById("list");
el.addEventListener("click", check , false);
I understand that preventDefault is a method and not a property . I did not understand how they are doing a e.preventDefault in the if condition .I checked in chrome and did not find any property called preventDefault for e . There is a function under proto called preventDefault. Am I correct in assuming that all methods can be changed to a property removing the () and you can use it in your code to test if that method is available or not ?
the double asterisks should not be there.
if(e.preventDefault) will work because if checks if the passed argument isn't null. So when preventDefault function will be defined, the condition will be true.
This is just for checking cross browser support. IE 8 or under won't support preventDefault, they use returnValue.
//check preventDefault function is exists in event handler 'e'
if (e.preventDefault) {
// if browser support preventDefault, call preventDefault();
e.preventDefault();
}
Here is the thing.
I'm need to open a new tab and draw something on the new opened tab.
I add event listener like that:
div3.addEventListerner("onmousedown",MouseDown(NewWindow.event),false);
But the firefox throw errors about the code in the MouseDown() function when the page is loading. The error is not throwed when I move the mouse.
function MouseDown(event)
{
if(!event)
{
var event = window.event;
}
X = event.pageX;//Throw error here.
Y = event.pageY;
So, there is anyone who knows how to fix this Problem?????
Remove the var from var event = window.event. The variable is already declared (as an argument), so re-declaring it with var can only lead to problems.
To be specific, due to hoisting, here is what your code boils down to:
function MouseDown(event) {
var event; // = undefined
if( !event) { // always true
event = window.event; // undefined in modern browsers
}
X = event.pageX; // ERROR!
}
Without the var, all is well!
When you're using addEventListener(), Event object is passed automatically in all browsers supporting the said method. However, you're calling your eventhandler immediately in argument. Instead you should pass a reference:
div3.addEventListener("mousedown", MouseDown, false);
Notice also "mousedown" without on. In the handlerfunction, event always exists, no need to check it for older IEs, since they don't support addEventListener.
I am trying to simulate keypresses in a web application, it is for an embedded system but it uses a Webkit derived browser. I have tested the code in Chrome and get the same error.
I tried to use code snippets from this example from Yahoo, but I keep getting the same error when firing the event using dispatchEvent. "target" is an HTML element in the DOM tree.
function fireEvent(target) {
var evt = document.createEvent("UIEvent");
evt.initEvent("keypress", true, true);
target.dispatchEvent(evt);
}
It always throws:
"Error: UNSPECIFIED_EVENT_TYPE_ERR: DOM Events Exception 0"
I have tried createEvent("Events") as well and it always boils down to the same exception, both on the embedded system and in Chrome.
Ok, when doing further testing, it seemed that when all key event parameters was properly initialised, then dispatchEvent worked without fireing an exception.
The following code works.
function fireEvent(target) {
var evt = document.createEvent("Events");
evt.initEvent("keypress", true, true);
evt.view = window;
evt.altKey = false;
evt.ctrlKey = false;
evt.shiftKey = false;
evt.metaKey = false;
evt.keyCode = 0;
evt.charCode = 'a';
target.dispatchEvent(evt);
}
Keypress is an UIEvent. You should use initUIEvent( 'type', bubbles, cancelable, windowObject, detail ) rather than initEvent(). But for firefox, which implements a keyEvents, you should create a KeyEvents and initKeyEvents().
This one is old thread, just to update it I am adding another answer so that it makes more sense to any one.
initEvent() is deprecated It is still supported in some browsers but avoid using it.
There is better concise way to create events like this
function fireEvent(target) {
var event = new Event('build');
// Listen for the event.
target.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
target.dispatchEvent(event);
}
To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.
For example, the event could be created as follows:
var event = new CustomEvent('build', { 'detail': target.dataset.time });
Reference: Creating and Triggering Events
Let me just first point out to any IE users right now (this is not a problem in Chrome, Safari or Firefox) hint hint ;)
So... I have a issue with my tooltips in IE, I have a onmouseover listener for all the elements which are to be hoverable and then in my mouseover function I have a very basic cross browser declaration as such...
var event = e || window.event,
el = event.target || event.srcElement;
I've been having issues with the window object not existing in IE or something, this has been a issue after I added a flag to ignore mouseover's from one element mouseover on the way to the tooltip itself (during the time cycle allowed, 300ms). In other words the flag is to ignore mouseovers on route to the tooltip from the original mouseover.
So that logic looks like this...
loadtip.refMouseOver = function (e) {
var event = e || window.event, el = event.target || event.srcElement;
//console.log(window); // <-- throws error in IE (Member not found)
// Reset the lastHoveredRef data.
tipManager.lastHoveredRef = null;
tipManager.lastHoveredRef = [el, event];
// true means there is a tip open still, so if no tip is open.
if (tipManager.tipState !== true) {
tipManager.processTip(el, event);
} else {
return; // do nothing
}
}
The "Member not found" error will occur when I hover from one element quickly to the next in IE with the tooltip still open.
I read about window.open and close stuff with a try catch but I didn't see how that was relevant. Any help is greatly appreciated.
Ok I have found the problem.
To sum it up, basically IE will not pass a event to another function if that function call is within a setTimeout.
So you can trick IE by creating a copy of the event and passing that, here is a example of that...
var eventCopy = {};
for (var i in event) {
eventCopy[i] = event[i];
}
Then just send your function the eventCopy, even though this is a 'total' hack.
setTimeout(function () { yourFunction(eventCopy), yourDelayTime);
And voila it will work.
I should add, that Internet Explorer will merely create a reference to the global window event which is why we need the copy of event. This is because by the time setTimeout calls the function, windows.event has already passed,
Bottom line... don't try to send a event inside a setTimeout because IE won't accept it. This is true for IE 6, 7 & 8 from my testing.
I realize this question/answer is pretty old and seems to be resolved. That being said, I have another alternative I've used to handle a similar -- yet slightly different -- issue with 'Member Not Found' in IE versions prior to MSIE 9. I hope this helps someone out! ...this can also be used to work around issues with Firefox not having window.event.
First I extended jQuery and added a function to get the MSIE version or -1 if the browser is non MSIE. You can do the same or just create a pure JS function to accomplish this. Then create an event override function (it might be necessary to add a global 'event' variable in some cases), that's more of a per individual situation basis. Then override the event in your event handler(s) as needed.
Extending jQuery
// So this will give you the version of IE (or for non IE browser -1)
$.fn.msieVersion = function()
{
if ( navigator.userAgent.toLowerCase().indexOf( 'msie' ) !== -1 ) {
return document.documentMode;
}
return -1;
};
Override the global event
var setEvent = function( evt ) {
// Set the event if MSIE version is >= 9 or is -1 which means it's not IE
if ( $.fn.msieVersion() >= 9 || $.fn.msieVersion === -1 ) {
// NOTE: I have a global 'event' variable I'm using that comes from another previously loaded JS file
// Why? I didn't do it. I'm updating some SUPER old code the best I can. (old enough it has references to Netscape....)
event = evt || window.event;
}
return true;
};
Usage Example
$( 'img.myImageID' ).bind('mouseover mouseout', function ( evt ) {
setEvent( evt ); // Override the event
// DO WORK! ...continue all other awesomeness here!
// Maybe setTimeout(...)
};
Following is my JavaScript (mootools) code:
$('orderNowForm').addEvent('submit', function (event) {
event.preventDefault();
allFilled = false;
$$(".required").each(function (inp) {
if (inp.getValue() != '') {
allFilled = true;
}
});
if (!allFilled) {
$$(".errormsg").setStyle('display', '');
return;
} else {
$$('.defaultText').each(function (input) {
if (input.getValue() == input.getAttribute('title')) {
input.setAttribute('value', '');
}
});
}
this.send({
onSuccess: function () {
$('page_1_table').setStyle('display', 'none');
$('page_2_table').setStyle('display', 'none');
$('page_3_table').setStyle('display', '');
}
});
});
In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the event object does not have a preventDefault method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).
Any Help?
in IE, you can use
event.returnValue = false;
to achieve the same result.
And in order not to get an error, you can test for the existence of preventDefault:
if(event.preventDefault) event.preventDefault();
You can combine the two with:
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.
Try out this fiddle to see the difference in event binding.
http://jsfiddle.net/pFqrY/8/
// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
alert(typeof(event.preventDefault));
});
// preventDefault missing in IE
<button
id="htmlbutton"
onclick="alert(typeof(event.preventDefault));">
button</button>
For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.
e = $.event.fix(e);
After that e.preventDefault(); works fine.
I know this is quite an old post but I just spent some time trying to make this work in IE8.
It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.
Let's say that we have this code:
$('a').on('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.
Even if I set returnValue property directly to false:
$('a').on('click', function(event) {
event.returnValue = false;
event.preventDefault();
});
This also won't work, because I just set some property of jQuery custom event object.
Only solution that works for me is to set property returnValue of global variable event like this:
$('a').on('click', function(event) {
if (window.event) {
window.event.returnValue = false;
}
event.preventDefault();
});
Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.
UPDATE:
As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
Tested on IE 9 and Chrome.
To disable a keyboard key after IE9, use : e.preventDefault();
To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;
If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :
try {
e.keyCode = 0;
}catch (e) {}
Here is a full example for IE7/8 only :
document.attachEvent("onkeydown", function () {
var e = window.event;
//Ctrl+F or F3
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
//Prevent for Ctrl+...
try {
e.keyCode = 0;
}catch (e) {}
//prevent default (could also use e.returnValue = false;)
return false;
}
});
Reference : How to disable keyboard shortcuts in IE7 / IE8
Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build. Let me know your results with it. Everything executes fine on this end in Safari, FF, Opera on OSX. It is exclusively for fixing a problematic IE8 bug, and may have unintended results:
function ie8SafePreventEvent(e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.stop()
};
e.returnValue = false;
e.stopPropagation();
}
Usage:
$('a').click(function (e) {
// Execute code here
ie8SafePreventEvent(e);
return false;
})
preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.
return false in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
I was helped by a method with a function check. This method works in IE8
if(typeof e.preventDefault == 'function'){
e.preventDefault();
} else {
e.returnValue = false;
}