avrx
avrx

Reputation: 31

Javascript: IE event.preventDefault is null or not an object

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);  

Upvotes: 2

Views: 10731

Answers (2)

Spudley
Spudley

Reputation: 168685

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().

Upvotes: 0

slebetman
slebetman

Reputation: 113866

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   
};

Upvotes: 6

Related Questions