1

This is my javascript code

var helper = document.getElementById("helper");

helper.style.position = "relative";
helper.style.width = "50px";
helper.style.height = "50px";
helper.style.border = "1px solid #000";

function move() {
    helper.style.left = event.offsetX + "px";
    helper.style.top = event.offsetY + "px";
}

and my html code

<div id="grid" onmousemove="move()" onmousedown="down()">
    <div id="helper"></div>
</div>

But when I call that function nothing happens. I want that variable helper to bi global and everything pre-initialized so I don't have to initialize everything all over again when function is called

1

1 Answer 1

4

Your move function does have access to the helper variable. My guess is that the code you've shown is in a script element above the helper element on the page, and so when your var helper = document.getElementById("helper"); line runs, the element doesn't exist yet.

Also note that your move handler is relying on IE-specific behavior (a global event object). While this behavior is also provided by some other browsers for compatibility, it's not provided by all. To make it more broadly compatible, accept event as an argument:

function move(event) {
    // ...
}

...and update your DOM0 handlers like so:

<div id="grid" onmousemove="move(event)" onmousedown="down(event)">

That works because the scope in which the code in an onXYZ handler is called always has an event symbol, even if there isn't a global one.

Or, of course, use addEventListener (attachEvent on older IE versions).

Sign up to request clarification or add additional context in comments.

1 Comment

one more question. Look this jsfiddle.net/KkqX2 Why is it always "reloading" and when I move my mouse it follows it but it kinda restart and showing that small div at up-left corner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.