Search code examples
javascripteventsmouseeventkeyevent

How to use multiple javascript events in one HTML doc?


I have a page with 2 javascript events, one triggered from the mouse, the other from the keyboard. When I load the page I can get one or the other to work, but not both. If I press a key first that function will run, but then I cannot do the mouse click or another keystroke. And vice versa. I know jQuery makes this easier, but I'd rather not have my users download that for each page, so I'm trying to do this the old fashioned way. I have read as much about javascript events as I can find but I'm stuck here with this one ...

thanks in advance, Brad. NOTE: in Chrome and Safari I get the above results, Firefox and Opera will only work with the keystroke function

<html>
<head>
<script>
function create(event) {
var x=event.clientX-14;
var y=event.clientY-33;
var output = document.write("<p id=\"text\" style=\"background-color: white; position:    absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M@jesty!</p>");
}
function type(event)
{
var letter_in = event.keyCode;
var letter = String.fromCharCode(letter_in);
//var shift = event.shiftKey;
//if (shift === false) {letter = String.toLowerCase;}
document.write(letter);
}
</script>
</head>

<body onmousedown="create(event)" onkeydown="type(event)">

</body>
</html>

Solution

  • It's because you're using document.write() which clears everything else on the page, including your handlers.

    Calling document.write() after the document has been loaded implicitly calls document.open(), which clears the document.

    So to fix this, you want to use something like innerHTML to only update the contents of an element within your page.

    See this example:

    <html>
      <head>
    
      </head>
    
      <body onmousedown="create(event)" onkeydown="type(event)">
        <div id="foo"></div>
    
        <script>
          function create(event) {
            var x=event.clientX-14;
            var y=event.clientY-33;
            var output = document.getElementById("foo").innerHTML = "<p id=\"text\" style=\"background-color: white; position:    absolute; top:" + y + "px;left:" + x + "px;\";>You're Text, your M@jesty!</p>";
          }
              function type(event)
              {
                var letter_in = event.keyCode;
                var letter = String.fromCharCode(letter_in);
                //var shift = event.shiftKey;
                //if (shift === false) {letter = String.toLowerCase;}
                document.getElementById("foo").innerHTML = letter;
              }
        </script>
      </body>
    </html>