asutherland
asutherland

Reputation: 2969

Javascript, passing on a mouse event

I would like a cross modern browser way to take a mouse event from one html element and pass it on to another.

eg.

el1.addEventListener('mousemove', function(e) {
  el2.trigger('mousemove', e);
});

el2.addEventListener('mousemove', function(e) {
   //THIS SHOULD BE CALLED WHEN EITHER el1
});

a jquery solution is ok but I would prefer a non-jquery solution. Is this simple?

Upvotes: 1

Views: 3998

Answers (4)

Nick Rolando
Nick Rolando

Reputation: 26167

Here is the correct code

var el1 = document.getElementById('el1');
var el2 = document.getElementById('el2');

el1.onmousemove = function(e) {
    alert('el1 event');
    el2.onmousemove(e);
};
el2.onmousemove = function(e) {    
    alert('el2 event');
};

demo

This is good if you want the event argument e to pass over to el2's event. This updated demo shows mouse position being passed over.

Upvotes: 2

rlemon
rlemon

Reputation: 17666

el1.addEventListener('mousemove', handler, false);
el2.addEventListener('mousemove', handler2, false);
function handler(e) {
    // do some stuff
    handler2.call(el2, e); // pass el2 as this reference, event as the argument.
};

not too sure if this is what you are looking for, just name the event handlers and trigger the one off the other.

if you do not need the this reference in the second handler, use handler2(e); instead.

further readings:
Function.prototype.call

Here is a half-baked demo passing the mouse event args. I'm unsure how well supported layerX/Y is, I just used it to show the demo.

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

If you accept a jQuery answer then here's the code:

// el1 and el2 are the jQuery objects of the DOM elements
el1.mousemove(function (event) {
    el2.mousemove(event);
});

In pure javascript:

el1.onmousemove = function(e) {
    el2.onmousemove('mousemove', e);
};

el2.onmousemove = function(e) {

};

Upvotes: 0

hereandnow78
hereandnow78

Reputation: 14434

native should work like that

var evt;
el1.onmousemove = function() {
  evt = document.createEvent('MouseEvent');
  evt.initEvent('mousemove', true, true);
  el2.dispatchEvent(evt);
}

You can read up on element.dispatchEvent here:
https://developer.mozilla.org/en-US/docs/DOM/element.dispatchEvent

Upvotes: 0

Related Questions