Mostafa
Mostafa

Reputation: 39

onmousemove event

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';


    }

Upvotes: 0

Views: 2668

Answers (1)

Jared Farrish
Jared Farrish

Reputation: 49248

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.

Upvotes: 3

Related Questions