Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Create Custom Events in JavaScript to Program with HTML

The standard events provided with JavaScript perform well for most common tasks. But, sometimes, you will need a custom event. For example, you must have a method of performing a click, and JavaScript provides a standard event to handle this need. However, there are times when you need to pass information that the makers of JavaScript can’t foresee. In this case, you must create a custom event.

How to work with the CustomEvent object in JavaScript

The CustomEvent object provides the means for creating a new event — one that isn’t part of JavaScript by default. The CustomEvent object is deceptively simple. All it contains are the two properties described in the following list:

  • Event name: A string containing the name that you want to use for the event. The name can be anything you want, but it can’t contain any whitespace characters, such as the space. Use an underscore (_), if desired, to separate words.

  • Event data: An object literal that contains the data you want to pass as part of the event. This part of a custom event can become quite complex because you can pass any amount of data in any form you want, as long as the data fulfills the object literal format. The event data comes in two forms:

    • Standard data: You can provide information for any of the properties supported by the standard Event object. Most developers define the bubbles and cancelable properties as a minimum.

    • Custom data: A custom event can contain custom data in any form. You must avoid using the names of any standard properties. For example, you can’t give a custom property the name bubbles. Many developers use the detail property to contain details about the custom event, but this is only a convention, and you’re free to use any form you see fit.

How to create the custom event code in JavaScript

JavaScript makes it quite easy to create custom events of your own. These events could be anything. There are many uses for custom events, but they all follow the same pattern. This example begins the global custom event object shown here.

// Define a new event.
var SpecialEvent = new CustomEvent(
  "SpecialMessage",
  {
   detail:
   {
     message: "Hello There",
     time: new Date()
   },
   bubbles: true,
   cancelable: true
  });

Notice that this event relies on a form of object literal. However, notice how detail is actually a nested object literal. You can nest information as many levels deep as needed. If you later want to change some feature of the event, you can do so. For example, to change the message, you would use code similar to this:

SpecialEvent.detail.message = "A new message!";

Now that you have a custom event to use, you need to go through three phases to implement it. First, you must assign the event to a control. The example uses a label and tells the application to make the assignment as part of the form loading process using: <body onload="AssignEvent()">. Here’s the code you need to assign the event to the label:

function AssignEvent()
{
  // Obtain the object reference.
  var Label = document.getElementById("CustomLabel");
 
  // Assign an event to the object.
  Label.addEventListener(
   "SpecialMessage", HandleEvent, false);
}

Here you see it a standard click event for the SpecialMessage custom event. Whether you assign a standard or custom event, the technique is the same.

The second phase of implementing a custom event is firing the event. This example relies on a button to perform the task, but any action could fire the event. All you need is an action where you can attach code to perform the task of firing the event. Here’s the event firing code used for this example:

function FireEvent()
{
  // Obtain the object reference.
  var Label = document.getElementById("CustomLabel");
 
  // Fire the event.
  Label.dispatchEvent(SpecialEvent);
}

The dispatchEvent() function performs the actual work. Notice that you fire the event using the event object you created earlier. If you had wanted, you could assign values to any of the content found in the custom event. For that matter, you could create new content as needed as long as the recipient knows how to work with the new content.

The third phase of implementing a custom event is providing the event handler. The event handler receives the custom event from the control that’s assigned to the event handler. Here’s the event handler used in this case:

function HandleEvent(event)
{
  // Display the event information.
  document.getElementById("CustomLabel").innerHTML =
   "Control: " + event.currentTarget.id +
   "<br />Message: " + event.detail.message +
   "<br />Time sent: " +
   event.detail.time.toTimeString();
}

All that this event handler does is display the custom event information onscreen.

image0.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.