0

I want to change the left and top style element with javascript on an onmousemove event, but it does not work.

My code for the onmousemove event:

function mymove(e)
{
var event=new MouseEvent(e);
    x = 20;
    y = 10;     

    document.getElementById('mye').style.left = event.pageX + x+'px' ;
    document.getElementById('mye').style.top = event.pageY - y+'px';


    }
skaffman
  • 398,947
  • 96
  • 818
  • 769
Mostafa
  • 39
  • 1
  • 2
  • 5
  • 2
    Don't do the `var event=new MouseEvent(e);` statement. The function argument already is the correct event object. Just use it. – Šime Vidas Feb 04 '12 at 14:16

1 Answers1

3

Guessing on the markup and CSS. Also, I think the e properties might change per browser. This works in Firefox (9).

CSS

#mye {
    height: 25px;
    width: 250px;
    position: absolute;
    background: #ddd;
}

Markup

<div id="mye">Content</div>

Javascript

var mymove = function (e) {
    var x = 20,
        y = 10,
        mye = document.getElementById('mye');

    mye.style.left = (parseInt(e.clientX) + x) + 'px';
    mye.style.top = (parseInt(e.clientY) - y) + 'px';
};

// Don't forget to add this in an onload or ondomready.
document.getElementById('mye').onmousemove = mymove;

http://jsfiddle.net/3YdEa/6/

And note, as Jeffrey Sweeney mentions, attaching to the window.onmousemove is probably more common:

window.onmousemove = mymove;

http://jsfiddle.net/3YdEa/7/

Here is Quirksmode on the mouse event position property situation. This is a few years old, however.

Here's another StackOverflow question, and of course jQuery's $.mousemove(), which will eliminate the differences between browsers.

Community
  • 1
  • 1
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104