What is an event handler?

An event is an action performed by the user or the browser itself. Such as Click, Mousemove, and Load are the names of events. Functions that respond to an event are called event handlers (or event listeners). Event handler names begin with ‘on’, so the event handler for the Click event is onclick and the event handler for the load event is onLoad. There are several ways to specify handlers for events.

HTML event handler

Each event supported by an element can be specified using an HTML feature with the same name as the corresponding event handler. The value of this feature should be JavaScript code that can be executed.

// Here is a brief introduction, if you need to know more about dynamically created functions, the way to extend scope. Do your own research (Little Red Book 3rd Edition P349)<input type='button' value='onclick me' onclick='alertMessage()'>

<script type='text/javascript'>
    function alertMessage() {
        alert('click me')}</script>
Copy the code

Disadvantages of specifying event handlers in HTML

1. Time lag, because the user may trigger an HTML element as soon as it appears on the page, but the time handler may not be ready to execute at that time. For the example above, assume that the alertMessage() function is defined below the button, at the bottom of the page. If the user clicks the button before the page parses alertMessage(), an error is raised. To do this, you can add a try-catch judgment when defining the handler.

<input type='button' value='onclick me' onclick='try{alertMessage()}catch(e) {} '>

<script type='text/javascript'>
    function alertMessage() {
        alert('click me')}</script>
<! Here is only one of them. If you are interested in knowing more, you can check the information.
Copy the code

DOM0 level event handler

Assigns a function to an event handler property. It is supported by all modern browsers for a simple reason and the cross-browser advantage

// The corresponding event handler is not specified until the following code runs, and the button may not trigger the alert() method
let btn = documnet.getElementById('btn');

btn.onclick = function() {
    alert('click me')

    //this executes a reference to the element
}

// You can also delete the specified method
btn.onclick = null
Copy the code

Dom2-level event handler

AddEventListener () and removeEventListener (). All DOM nodes contain these two methods, which take three parameters: the name of the event to process, the event handler function, and a Boolean value. This Boolean value represents the call event handler for the true – capture phase; False – Bubble phase call

let btn = documnet.getElementById('btn');

// Why not use anonymous function writing, remove method needs to pass the same parameter as the add
function handler(){
    Like dom0-level event handlers, the event handlers added here are scoped to the element to which they are attached
    alert('click'.this.id)
}

btn.addEventListener('click', handler, false);

// The parameters need to be equal
btn.removeEventListener('click', handler, false);
Copy the code

What are the benefits of using dom2-level event handlers

Multiple event handlers can be added with the DOM2-level handler. And it’s triggered sequentially, from the top down

let btn = documnet.getElementById('btn');

function handler1(){
    alert('click1'.this.id)
}
function handler2(){
    alert('click2'.this.id)
}

btn.addEventListener('click', handler1, false);
btn.addEventListener('click', handler2, false);
Copy the code

IE event handler

AttachEvent () and detachEvent (); Receives the same two parameters: event handler name, event handler function; Since IE9 previously only supported event bubbling, event handlers added through attachEvent() were added to the bubbling phase

let btn = documnet.getElementById('btn');

function handler(){
    alert('click'.this.id)
}
/ /!!!!!! Notice that this is onclick, not click
btn.attachEvent('onclick', handler)
// Remove method
btn.detachEvent('onclick', handler)

// The main difference between attachEvent() and using dom0-level methods is the scope of the event handler. Point to window in IE
btn.attachEvent('onclick'.function() {alert(this= =window)}) // true
Copy the code

What is the difference between using IE level event handlers and DOM2 level event handlers

Multiple event handlers added using IE handlers. And it triggers it in the opposite direction, from the bottom up

let btn = documnet.getElementById('btn');

function handler1(){
    alert('click1'.this.id)
}
function handler2(){
    alert('click2'.this.id)
}

btn.attachEvent('onclick', handler1);
btn.attachEvent('onclick', handler2);

// click2 ---> click1
Copy the code

A generic cross – browser event handler

For reference only

const EventUtils = {
    / / sight, respectively dom0 | | dom2 | | way, IE to bind event
    // Add events
    addEvent: function(element, type, handler) {
        if (element.addEventListener) {
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent) {
            element.attachEvent(“on” + type. handler);
        } else{element[" on "+ type] = handler; }},// Remove the event
    removeEvent: function(element, type, handler) {
        if (element.removeEventListener) {
            element.removeEventListener(type, handler, false);
        }else if(element.detachevent) {element.detachevent (" on "+ type, handler); }else {
            element[“on” + type] = null; }}// Get the event target
    getTarget: function(event) {
        return event.target || event.srcElement;
    },

    // Get a reference to the event object, get all the information about the event, and ensure that the event is always available
    getEvent: function(event) {
        return event || window.event;
    },

    // Prevent events (mainly event bubbling, since IE does not support event capture)
    stopPropagation: function(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        }else {
            event.cancelBubble = true; }}// Cancel the default behavior of the event
    preventDefault: function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false; }}}Copy the code