Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Object on Firefox

Sorry, this seems to be a great crowd pleaser... That should be why firefox has not changed their code to be fully compliant with the Event object just like Chrome. I've done my homework, tried several solutions given here on StackOverflow, but nothing seems to work. I have this code:

function xpto(e) {
if( !e ) e = window.event;
  var x = e.target||e.srcElement;
alert(x);
    ........
}

The call is being made like:

<svg id="graph-svg" onclick="xpto(event)" style="outline: none;" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

Yes... It's an svg element that I'm trying to get on click. I have not put the complete code because it was not relevant to the question. Bottom line, the

alert(x)

is always alerting with undefined on Firefox, and working on Chrome like a charm. I can grab the Event on Firefox, but the "x" always cames undefined.

In firefox on the DOM description either Event and SVG are supported. Event is even defined with the "target" and "srcElement" properties for backwards compatibility.

I'm using Firefox 20 on Ubuntu... Can anyone help?

like image 214
Pedro Bento Avatar asked Jan 13 '23 17:01

Pedro Bento


2 Answers

After a reply from d'alar'cop I went to the code and found out that the argument that works in firefox is not "event" or "Event" but "evt"... The console in Firebug showed this:

    function onclick(evt) { xpto(event) }

So with that I realized that the handler was being called with "event" rather than the original argument "evt". Then when it felled into the handler the "event" was going "null" ... undefined.

like image 56
Pedro Bento Avatar answered Jan 19 '23 12:01

Pedro Bento


Many times I see event handler inlined in HTML code, instead to rely on the more powerful event listeners.

Instead to use onclick why don't you attach a listener to the SVG element? You could try this:

var addListener = function (element, event, callback) {
    // We define a cross-browser function
    if (window.addEventListener) {
        // Mozilla/Webkit/Opera
        element.addEventListener(event, callback, false);
    } else {
        // IE
        element.attachEvent('on' + event, callback);
    }
};

// Then we attach the event listener to the SVG element
addListener(document.getElementById('graph-svg'), 'click', function (evt) {
    // Here you can manage the fired event
    alert(evt);
});

or, using jQuery:

$('#graph-svg').on('click', function(evt){
    alert(evt);
});

You can try it with this fiddle (tested with FF 20.0 and Chrome 26 on Ubuntu 12.10).

Of course, inline handlers aren't always evil, but many times they're not the solution, IMHO.

like image 24
Ragnarokkr Avatar answered Jan 19 '23 11:01

Ragnarokkr