4

I am trying to get the image wherever the mouse is clicked. But getting this error:

Uncaught ReferenceError: evt is not defined onmousedown

HTML:

<html>
<head>
    <title>Image move</title>
    <script type="text/javascript" src="pos.js">
    </script>
</head>
<body onmousedown="display(evt)">
<img id="myimage" height=300 width=300 src="pos.jpg" style="position:absolute;top:100px;left:100px"; alt="mypos" />
</body>
</html>

JS:

function display(evt)
{
    var dom = document.getElementById("myimage");
    dom.style.top = evt.clientY+"px";
    dom.style.left = evt.clientX+"px";
}

Do I have to write event explicitly? What's the problem?

halfer
  • 19,824
  • 17
  • 99
  • 186
Robin
  • 5,366
  • 17
  • 57
  • 87
  • I think that brackets are reserved for defining functions and other things. I don't think you can use brackets in the name of a function, it'll confuse JavaScript. –  Aug 18 '14 at 21:25

1 Answers1

5

Just do onmousedown="display(event);". The active event is event, not evt.

When an event such as onmousedown occurs, the piece of JavaScript associated with it gets executed in a scope that defines the event object. Some browsers make it also available globally as window.event, as elaborated by this response, meaning you wouldn't have to explicitly pass it to the display function.

Community
  • 1
  • 1
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
  • 1
    Yes, it does solve the problem. Can you please elaborate a little. – Robin Aug 18 '14 at 21:27
  • 1
    @Robin: when you use an `on*` HTML attribute, the browser generates a function of the form `function(event) { /* attribute content */ }` . Therefore in order to refer to the event object, you have to use `event`. You used `evt`, but it's not defined anywhere, neither implicitly nor explicitly. – Felix Kling Aug 18 '14 at 21:33
  • @FelixKling Thank you, now it makes more sense. – Robin Aug 18 '14 at 21:37