JavaScript: Click Me!

When working on HTML and JavaScript projects it is very likely that you will want to respond to events. For instance you may want to run some JavaScript code when a button is clicked.

Examples of HTML events:

  • When a user clicks the mouse (onClick event)
  • When a web page has loaded (onLoad event)
  • When the mouse moves over an element (onMouseOver and onMouseOut events)
  • When an input field get the focus (onFocus event) or loses the focus (onBlur event)
  • When an input field is changed (onChange event)
  • When an HTML form is submitted (onSubmit event)
  • When a user strokes a key (onKeyPress event)

To assign events to HTML elements you can use event attributes within your HTML code. For instance:

<INPUT type="button" value="Click Me!" onClick="JavaScript: alert('Ouch!');">

Let’s look at a few examples:

onClick Event

See the Pen JS: onClick Event by 101 Computing (@101Computing) on CodePen.

onFocus and onBlur Events

See the Pen JS: onFocus Event by 101 Computing (@101Computing) on CodePen.


Did you notice? Using “this” as a parameter in the JavaScript function enables to access the form control that triggered the event. So the same function could be used for more than one form control.

onChange Event

See the Pen JS: onChange Event by 101 Computing (@101Computing) on CodePen.

onMouseOver and onMouseOut Events

See the Pen JS: onMouseOver onMouseOut Event by 101 Computing (@101Computing) on CodePen.

Form Validation using onSubmit Event

Look at how the onSubmit event can be used to perform some validation checks before sending the data/form accross.
This code shows that it is possible to confirm or cancel an event using the “return” keyword. (return true confirms the event whereas return false cancel the event)

See the Pen JS: Form Validation by 101 Computing (@101Computing) on CodePen.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!