Wednesday, December 7, 2005

DHTML III: Detecting the mouse click and coordinates

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/dhtml_iii_detecting_the_mouse_click_and_coordinates.htm]

Continuing my DHTML posts (DHTML I: Intro and Positioning Text, and DHTML II: Using Hidden Divs instead of Popup windows), there are more cool things you can do, such as detecting the mouse click and its coordinates. This is useful if you're trying to make a more complex UI or perhaps even a simple game. Perhaps the best way to flush this out is with an example. Say you want to be able to click a table cell, and have a yellow dot appear where ever you clicked. You could do this by first getting the mouse coordinates, and then positioning a div tag (which holds the image for the dot) to those coordinates.

Here's the code, then I'll explain it:

<HTML>
  <HEAD>
    <title>DetectClicktitle>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    <style>
      .divAbsPosition1
        {
          z-index: 1;
          left: 0px;
          position: absolute;
          top: 0px;
          visibility:hidden;
        }
    style>
    <script language=javascript>
     

    script>

  HEAD>
  <body MS_POSITIONING="FlowLayout">
    <form id="Form1" method="post" runat="server">
    <div id="DivDot" class="divAbsPosition1">
      <img src="dot.gif">
    div>
   
    <table border=1>
      <tr>
        <td>Click on next cell:td>
        <td width=300px height=100px onmousedown="doSomething()">
      Mouse coordinates: (<span id="span1">span>)
    td>
      tr>
   
    table>

    form>
  body>
HTML
>

The cell has an onclick that triggers a JavaScript method. This method gets the window event, from which it can get the mouse click coordinates. We then simply set the div tag to that position. It's surprisingly simple. There's also a deeper discussion of this here.

Of course, you could combine these three DHTML posts (positioning, visibility, and mouse clicks), and the JavaScript timer, to create simple games. For example, you could have another dot move by getting its position set by the timer, and then detect if you clicked that moving dot by comparing the mouse coordinates. There's a lot of potential.

No comments:

Post a Comment