Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the event object different coming from jquery bind vs. addEventListener

Why is it when I use the jQuery bind the event object I get back is different from the event object I get back using addEventListener?

The event object resulting from this jQuery bind does not have the targetTouches array (among other things) but the event from the addEventListener does. Is it me or is something not right here?

$(document).ready (function () {
    $("#test").bind("touchmove", function (event) {
        console.log(event.targetTouches[0].pageX);
        // targetTouches is undefined
    });
});

vs.

$(document).ready (function () {
    var foo = document.querySelectorAll('#test')
    foo[0].addEventListener('touchmove', function (event) {
        console.log(event.targetTouches[0].pageX);
        // returns the correct values
    }, false);
});
like image 906
yodaisgreen Avatar asked May 19 '10 06:05

yodaisgreen


1 Answers

That's because jQuery uses its own Event model.

jQuery simply copies and normalizes some properties from the original event, to the event object that you get as the first argument of the handler.

The copied properties are based on the DOM Level 3 Events Spec.

To get the original event object, you can:

$(document).ready (function () {
    $("#test").bind("touchmove", function (event) {
        var e = event.originalEvent;
        console.log(e.targetTouches[0].pageX);
    });
});

The originalEvent property is accessible and it will work, but is not documented, you can see how it's set behind the scenes in the jQuery.Event constructor.

like image 60
Christian C. Salvadó Avatar answered Oct 22 '22 05:10

Christian C. Salvadó