Skip to content

Instantly share code, notes, and snippets.

@aresnick
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aresnick/9da14e0e0659aac3e835 to your computer and use it in GitHub Desktop.
Save aresnick/9da14e0e0659aac3e835 to your computer and use it in GitHub Desktop.

A tiny example demonstrating how to use addEventListener to listen for mouse events in JavaScript

This is a tiny sketch demonstrating how to add some basic mouse interaction with an HTML element via JavaScript. There is a small, accompanying screencast you can watch here. Please let us know if you have any questions or issues!

Further doing

Modify the code so that:

  1. …on mousedown the square changes color, and on mouseup it changes back
  2. …each click changes the base color of the div
  3. …a doubleclick rotates the div

Further reading

<html>
<head>
<style>
#mySquare {
width: 100px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div id='mySquare'></div>
<script>
var square = document.getElementById('mySquare'); // grab our #mySquare element and store it in a variable
var changeColor = function(element, color) { // define a small function to let us change the color of an element
element.style.backgroundColor = color;
};
square.addEventListener('click', function() { changeColor(square, 'red'); }); // and add an event listener that changes the background-color of #mySquare to 'red' when we click
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment