event.target on Firefox

niko picture niko · Sep 17, 2011 · Viewed 35k times · Source
 var x = event.target||event.srcElement;
 document.getElementById(x.id).style.left =  200 + "px" ;
 document.getElementById(x.id).style.top  =  100 + "px" ;

Works fine on Google Chrome and IE but not on Firefox. Tried it on Google. Google says event.srcElement (works on IE but not on Firefox) so I have added event.target but still not working. Is there anymore changes I need to do to work on Firefox? By the way I'm using 3.5 version of Firefox.

   function up()
       {
            dragok = false;
            document.onmousemove = null;
            var x = event.target||event.srcElement;
            document.getElementById(x.id).style.left= 200 + "px" ;
            document.getElementById(x.id).style.top= 100 + "px" ;
       } 

Please help me to make it work on Firefox

Answer

user113716 picture user113716 · Sep 17, 2011

Make sure you define event as a formal parameter to the handler.

IE defines it globally, and Chrome defines it both in both places, so it works either way, but Firefox only defines it as a function parameter.

function up( e ) {
    //       ^-----------------------------------------------------+
    if( !e ) e = window.event; // <---needed this --- and this ->--+

    dragok = false;
    document.onmousemove = null;
    var x = e.target||e.srcElement; // <--- and these
    document.getElementById(x.id).style.left= 200 + "px" ;
    document.getElementById(x.id).style.top= 100 + "px" ;
}