Javascript is a good starting point for anyone interested in games programming. That's because all they need is a standard text editor (such as notepad or Pico) and a web browser. With those, and a little javascript code, the programmer can quickly produce some simple animation that can be controlled by the user (as discussed in How to Make Web Page Animations Using Javascript: Creating a Simple Javascript Game with the setTimeout method).
However, before long, the programmer want to do more than just move an object and that the user has clicked a mouse button. The programmer will start to need to know where the mouse cursor is positioned on the screen. Fortunately this is another task that Javascript makes easy.
Not All Web Browsers are the Same
Javascript is useful to application developers because they know that it is universally accepted by the creators of web browsers. This means that the programmer can write an web based application that will run correctly with Firefox or Internet Explorer.
However, that's not to say that all browsers will run Javascript in the same way. Quite often Internet Explorer will handle web page objects in one way and all other web browsers will handle them in another. This is an important point for Ajax developers (see A Simple Introduction to Ajax: How to implement Ajax Into a Web Page – Easily), and it's important point for games developers. In this case some code is required that will identify the browser type being used:
Now the correct code will run according the browser being used.
Obtaining the Mouse Pointer Coordinates with Javascript
In this example a div area will be updated with the location of the mouse cursor when the user clicks on the screen. Therefore, a div with a defined id is required:
Next the function that is going to do all of the hard work is required along with any variables that it will be using:
Now the function must decide which screen properties it is going to use. If the web browser is Microsoft Internet Explorer then:
- X = window.event.clientX
- Y = window.event.clientY
If any other web browser is being used then:
- X = e.pageX (where e is the screen event)
- Y = e.pageY
The coordinates can be obtained correctly in this way:
And the div area can be updated at the end of the function:
Finally the function needs to be assigned to a event:
If this is saved as a .html file and then viewed with a web browser then the screen will be updated with the coordinates of the mouse whenever the user clicks on the screen.