Event Listeners

What is an event listener?

Visual1

Everything you see on a website has a number of different events you can "listen to".

Common events include (but are not limited to):

  • click
  • mouseup
  • mousedown
  • mouseover
  • keypress
  • keydown
  • keyup
  • focus
  • blur

You can find a full list of HTML5 events here: HTML5 Events

Rainbow Clicking

Here we use an event listener to listen for a click on the canvas. When the click is received we draw a rainbow design radiating out from the click.

Editor (write code below)
var canvas = document.getElementById('event_listeners_example1'); var context = canvas.getContext('2d'); var increment = 20; var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; function drawColor(centerX, centerY, specificIndex, generalIndex) { context.save(); context.globalAlpha = 1 - (generalIndex * 0.05); context.fillStyle = colors[specificIndex % colors.length]; var size = specificIndex * increment; var x = centerX - (size / 2); var y = centerY - (size / 2); context.clearRect(x, y, size, size); context.fillRect(x, y, size, size); context.restore(); } function drawColors(centerX, centerY, index) { for (var i=index; i>=0; --i) { drawColor(centerX, centerY, i, index); } } function rainbowAnimation(centerX, centerY, index) { drawColors(centerX, centerY, index); setTimeout(function() { if (index < 20) { rainbowAnimation(centerX, centerY, index + 1); } }, 20); } canvas.addEventListener('click', function(e) { rainbowAnimation(e.layerX, e.layerY, 1); }); context.save(); context.font = "20px serif"; context.textAlign = 'center'; context.fillText('Click Anywhere!', canvas.width / 2, 50); context.restore();
Message Log
This is a lesson, not a challenge, the code runs automatically.

But change it! Play with it! Click "Run" to see your changes.

Run
Run and Focus Canvas
Reset
Canvas (your drawing will display here)

Ready for the next lesson?

Next up, the "Functions" lesson >