Search code examples
javascriptjquerymouseeventjquery-events

Bind context when event binding on $(document)


The situation is like this: I have a div which we can get using $('#container') and a child div of this div is ('#tracker'). On tracker I bind a event as:

$(document).on('mousemove', '#tracker', function(e) {
    console.log(e.clientX);
}

However, I wish to bind it in context of the container, i.e. I wish functionality same as:

$('#tracker', '#container').onmousemove = function() { ... }

but applied to the document. Or suggestions stating otherwise

[EDIT] Sorry for vague original question.

If I try to cache, then I can do var v = $('#tracker', '#container') and then I can do v.onmousemove = function () { ... }

How does this work for:

$(document).on('mousemove', <cached in var>, function(e) {
    console.log(e.clientX);
}

Solution

  • Just extend the selector passed to .on() to only find #tracker elements that are inside a #container element:

    $(document).on('mousemove', '#container #tracker', function(e) {
        console.log(e.clientX);
    });
    

    If you want to cache the object in another variable there are a few ways you could do that. The first is the same as before, but you won't be using it when you call .on():

    var v = $('#tracker', '#container');
    
    $(document).on('mousemove', '#container #tracker', function(e) {
        // use v here
    });
    
    // you can also use v here
    

    Or, if you only ever need it inside of the event handler function, you could do it this way:

    $(document).on('mousemove', '#container #tracker', function(e) {
        var v = $(this);
        // use v here
    });