2. HTML Events

2.1. onclick


          onclick event handler is used to detect a mouse click HTML event on an element.  Several simple examples are shown below on how to use this event handler on an element.

<p onclick="alert('So I click you, now what?')">Click Me.</p>

          In the example above, when users click on Click Me an alert dialog box with the message So I click you, now what? will be shown.

<p onclick="this.innerHTML = 'It had been clicked'">Click Me.</p>

          The example above, replaces the content of the paragraph element Click Me to It had been clicked when a user clicks on the element.  Important keywords used here are this and .innerHTML. The keyword this refers to the element that uses it, in this case the paragraph element, while the keyword .innerHTML refers to the content of an HTML element.

          The next two example codes is to change the image: 


<img onclick="this.src='img_girl.jpg'" src="smiley.gif" width="100" height="100" style="border:5px solid black">



  1. <!DOCTYPE html>
  2. <html>
  3. <body>

  4.        <img id="image" onclick="changeImage()" src="smiley.gif" width="100" height="100" style="border:5px solid black">

  5.        <script>
  6.              function changeImage()
  7.              {
  8.                  image.src='img_girl.jpg';
  9.              }
  10.        </script>
  11. </body>
  12. </html>

The above two examples will achieve the same result.  

          The first sample uses this.src to change the image from smiley.gif to img_girl.jpg.  While the second sample code, calls the defined function changeImage when a user clicks on the smiley image.  Inside the function, the id of the img element which is image is used to enable the script to change images through img src attribute.  An alternative statement  to image.src='img_girl.jpg'; would be document.getElementById("image").src='img_girl.jpg';   as discussed in the previous lessons.  The advantage of the second example code, is that you can extend the functionality attached to the event handler onclick.