is it possible to change a button position with mouse event

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
PHPHelpNeeded
Forum Commoner
Posts: 83
Joined: Mon Nov 17, 2014 8:03 pm

is it possible to change a button position with mouse event

Post by PHPHelpNeeded »

I pieced together this js script to change the button's x position on MouseMove event, but the code is not working:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>


	<script>

		document.getElementById('mainDocumentBody').addEventListener('MouseMove', changeButtonPosition);

		function changeButtonPosition(){
			document.getElementById('button1').style.left = window.event.screenX;
			alert("x="+window.event.screenX+" y="+window.event.screenY);
		}

	</script>

	<div id='mainDocumentBody' border="2" width="100%" height="100%">
		<button id='button1'>New Game</button>
	 </div>

	<script>

	</script>
</body>
</html>
The alert is just to let me know the code is executing. But I still don't know if anything is happening or not, since I don't see anything happening yet.

I know the code has syntax errors perhaps, but I am here to find out how to do it the right way.

Some help with be appreciated.

Thanks.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: is it possible to change a button position with mouse ev

Post by Weirdan »

Scripts are executed when they are encountered. So by the time your script is executing the #mainDocumentBody element may not be present yet. Move the code after the div, or, better yet, into an onload event handler:

Code: Select all

window.addEventListener('load', function() {
   //  your code goes here
});
The second problem is your event name. Event names are case-sensitive, and mouse move event has to be spelled exactly like this: 'mousemove' (notice the case).
PHPHelpNeeded
Forum Commoner
Posts: 83
Joined: Mon Nov 17, 2014 8:03 pm

Re: is it possible to change a button position with mouse ev

Post by PHPHelpNeeded »

That worked thanks, but how do you actually change the x and y coordinate of button?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: is it possible to change a button position with mouse ev

Post by Weirdan »

Code: Select all

document.getElementsByTagName('button')[0].style.left = "200px"; // moves the button 200 px right, assuming the element has position:absolute and didn't have 'left' style property set
Post Reply