Anjan Dutta

Create and trigger custom events in JavaScript

Create and trigger custom events in JavaScript

Please watch this video for example implementation.

Sample code

HTML Code

1<html>
2 <head>
3 <title></title>
4 </head>
5 <body>
6 <div class="container">
7 <button class="btn" onclick="fireEvent()">Check for update</button>
8 <div class="content">
9 </div>
10 </div>
11 </body>
12</html>

CSS Code

1* {
2 box-sizing: border-box;
3 margin: 0px;
4 padding: 0px;
5}
6body {
7 height: 100vh;
8 width: 100%;
9}
10html {
11 min-height: 100vh;
12 width: 100%;
13}
14.container {
15 height: 100%;
16 width: 100%;
17 display: flex;
18 flex-direction: column;
19 justify-content: center;
20 align-items: center;
21
22}
23.btn {
24 background-color: green;
25 border: none;
26 border-radius: 3px;
27 padding: 10px;
28 color: #fff;
29}
30.btn:hover {
31 background-color: #fff;
32 border: 2px solid green;
33 color: green;
34 cursor: pointer;
35}
36.content {
37 display: flex;
38 justify-content: center;
39 align-items: center;
40 color: #fff;
41 height: 100px;
42 width: 100px;
43 margin: 40px;
44 border: 1px dotted #333;
45}

JavaScript Code

1document.addEventListener('myevent', function() {
2 let content = document.querySelector('.content');
3 content.style.backgroundColor = "green";
4 content.innerText = "Event Fired!";
5});
6
7function fireEvent(){
8 let el = document.querySelector('.btn');
9 let evt = document.createEvent('HTMLEvents');
10 evt.initEvent('myevent', true, true);
11 evt.eventName = 'myevent';
12 el.dispatchEvent(evt);
13}