Home >Web Front-end >JS Tutorial >How to create custom events in Javascript? (code example)

How to create custom events in Javascript? (code example)

藏色散人
藏色散人Original
2019-03-23 09:37:192599browse

How to create custom events in Javascript? (code example)

It is very simple to use javascript events and listeners. For example, I believe everyone is familiar with the following click event:

document.getElementById('my-button').addEventListener('click', function(){
    console.log('do something awesome!');});

The above code will click my- button, and this click event (as well as many other events) is already available to us. But what if you want to create your own events? It’s actually quite simple.

Create a custom event

In order to create a custom event, we can do as follows:

function create_custom_event(){
    
    var element = document.getElementById('my-button');
    
    element.classList.add('active')
    
    // 创建一个新的自定义事件
    var event = new CustomEvent('madeActive');
    // 分派元素上的事件
    element.dispatchEvent(event);}

Above we just created an event called madeActive custom event, so now anywhere in the application we can listen to this event and run some new functionality when that event is triggered.

Listening to custom events

Listening to custom events will work exactly like other event listeners in javascript. You attach addEventListener to your element and specify the event you are listening for:

document.getElementById('my-button').addEventListener('madeActive', function(){
    console.log('Awesome, my own custom Event!');});

Now, the above code will run whenever the madeActive event (or custom event) is fired.

Using custom events in your application can help you organize your code and make it more readable. It also makes maintenance easier because you can trigger events in one place and wherever the listener is listening, it can run the functionality you want.

Related recommendations: "javascript tutorial"

This article is an introduction to creating custom events in Javascript. I hope it will be helpful to friends in need!

The above is the detailed content of How to create custom events in Javascript? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn