Dan
Dan

Reputation: 57971

How to capture event on specified node only?

I have a markup like this:

<div id="largeField">
    <div class="small"></div>
    ......
    <div class="small"></div>
</div>

I try to catch mousemove on #largeField (in vanilla js, but that's not a requirement) with a code like this:

largeField.addEventListener('mousemove', function(event) {
    var elementData = event.srcElement.getBoundingClientRect();
    var eventX = event.pageX - elementData.left;

    // I just want to get event coordinates to draw something below the mouse

    event.stopPropagation();
    event.preventBubble = true;
    return false;
});

Fiddle

The problem is that I don't always get event catched on #largeField, but on other small elements too.

I don't want to filter on event.srcElement inside the callback, because when there will be 1000 of small elements, performance would bite.

I'm asking of the right way. I want the callback to be fired only on #largeField. I have asked that in the code!

Upvotes: 0

Views: 55

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075905

You can't, not reasonably. The mousemove event bubbles, and the only way to prevent that is to hook mousemove on all of your "small" elements and cancel the bubbling, which won't help anything and will probably make things worse.

But filtering on event.target (not event.srcElement, that's IE-only) shouldn't cause a performance problem.

largeField.addEventListener('mousemove', function(event) {
    if (event.target.id !== "largeField") {
        return;
    }
    // Logic here
});

Updated Fiddle

Upvotes: 1

Related Questions