Michael Yousef Michael Yousef - 3 months ago 13
jQuery Question

How to access $(this) and event in defined callback function

I'm trying to enable some touch controls through a callback function but I'm having trouble accessing the event as well as $(this) in my callback function. Right now the code looks as follows:


function touchControls(event) {
var mc = new Hammer(this);
mc.on("doubletap", function() {

Where '.img-responsive' is a class of images on my page.

When it tries to call event.preventDefault, I get an error that event.preventDefault is not a function. I thought the event was automatically passed to the variable called? I know when I did a named callback function with .on, event.preventDefault() worked perfectly fine. I assume it's different when I do it with .each, how do I properly access it?

Now, if I remove the event.preventDefault() line, when it logs $(this), I get a function. I was expecting to get individual elements so I could set touch controls for them, but that clearly didn't work. I tried to bind 'this' by:


But when I logged $(this), it was still a function and not the element I was expecting.

I'm basically just confused as to how to access $(this) and event within the defined callback function.


.each is not an event handler so it's callback function does not accept an event object. The method signature of the each callback function looks like this:

.each( function )

Type: Function( Integer index, Element element )
A function to execute for each matched element.

So you won't have an event object to reference but, more importantly, there will be no default event behavior to prevent.

Conversely, on does in fact setup event handlers. Its callback function does take an event as its parameter. You can handle your event management within your event handler code, inside the callback function for .on.

this will refer to your current element as you iterate. But inside your inner callback function there will be a different context (so a different this). Simply store a reference to the element in the outer scope:

function touchControls() {
    var $this = $(this);
    var mc = new Hammer(this);
    mc.on("doubletap", function(e) {