You can also create your custom events using Event and CustomEvent constructors. Events get fired when a user interacts with a web page such as click on a button, pressing keyboard keys, moving the mouse, etc.
You can execute a certain piece of code when a particular event is fired. This piece code should be inside an event handler function. To accomplish this, you have to attach that event to an element.
In the following example, we have 2 buttons to attach and detach a mousemove event. The event will be attached to the document. We also have an h1 element to display mouse coordinates. Please have a look over the code example and steps given below.
HTML & CSS
We have 4 elements in the HTML file (div, 2 button, and h1). The div element is just a wrapper for the rest of the elements.
The first button element has “Add” and the second button element has “Remove” as inner text.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.