DOM Event analysis in JavaScript (with code)

Source: Internet
Author: User
Tags event listener
What is the event? What's the use of events? This article will give you an overview of the event analysis of the DOM in JavaScript, and give you an introduction to the concept of events and the use of events.

Events

1. What is the event?

Let JS know the user behavior of the program, such as the user to click on a button in the HTML page and user input user name and password operations

<script>        var button = document.getElementById (' btn ');//        Get button element        Button.onclick = function () {//        Event binding            console.log (' You've ordered me ');    </script>

2. Registering events
The JS function is associated with the specified event, and the bound function becomes the handle to the event
When an event is fired, the bound function is called

Event properties for HTML elements

Represents the real Registration event feature
This method is not separated from the HTML structure and behavior effectively.

<body><button onclick= "Mylove ()" id= "Btn" > Buttons </button><script>    function Mylove () {        Console.log (' You've ordered me ');    } </script></body>

Event properties for DOM objects

Position the Document object on the THML page element
and returns the DOM object Body property, which implements various registration event functions

<body><button id= "btn" > button </button><script>    var btn = document.getElementById (' btn ');    Btn.onclick = Mylove;    function Mylove () {        Console.log (' You have ordered me ');    } </script></body>

Event Listener

In the Addevantlisener () method, call the method to indicate that the element adds an event listener

Body><button id= "btn" > button </button><script>    var btn = document.getElementById (' btn ');    Btn.attachevent (' onclick ', function () {        console.log (' XXX ');    })    function bind (Element,eventname, functionname) {        if (element.addeventlistener) {            Element.addeventlistener ()        }    } </script></body>

This in the event listener

When registering an event for a page using the AddEventListener () method, this refers to registering the event element
When registering an event for a page using the Attacheent () method, this refers to the Window object, which is not a registered event

<script>    var qyc =document.getelementbyid (' qyc ');    /*qyc.addeventlistener (' click ', Function () {        console.log (this);//this refers to the element of the current binding event    }); */    * Qyc.attachevent (' onclick ', function () {        console.log (this);//this refers to the Global Object (Window object)}) of the current environment    ; *    /bind (QYC, ' Click ', Function () {        console.log (this);//In different browsers, this will have different representations    });    function bind (element, EventName, functionname) {        if (Element.addeventlistener) {        } else {            Element.attachevent (' on ' + eventName, function () {                Functionname.call (Element)            });        }    } This is a compatible solution for versions prior to IE8 </script></body>

3. Remove Registration Events

The RemoveEventListener () method, which calls this method to indicate that the element is removing the event listener

<body><button id= "QYC" > button </button><script>    var qyc = document.getElementById (' qyc ');    function Mylove () {        console.log (' XXX ');    }    Qyc.addeventlistener (' click ', Mylove);    Qyc.addeventlistener (' click ', Function () {        console.log (' YYY ');    });    Qyc.removeeventlistener (' click ', Mylove);    function Unbind (element,eventname,functionname) {        if (element.removeeventlistener) {            Element.removeeventlistener (EventName, functionname);        } else {            element.detachevent (' on ' + EventName, functionname);        }    } </script></body>

4. Event Object

Represents the removal of the registration event prior to the IE8 version of the
The browser does not support the RemoveEventListener () method

<body><button id= "Qyc" onclick= "Mylove (Event)" > Buttons </button><script>    var qyc = document.getElementById (' Qyc ');    Qyc.addeventlistener (' click ', Function (event) {        Console.log (event);    });    Qyc.attachevent (' onclick ', function () {        console.log (window.event);    });    function bind (Element,eventname, functipnname) {        if (element.addeventlistener) {            Element.addeventlistener ( Eventname,functipnname)        } else {          element.attachevent (' on ' + eventName, function () {             Functipnname.call (element);}          );        }    } </script>

5. Get the target

Event object provides the target property to get the HTML element that triggered the current event
The event Events object provides the Currenttarget property, which gets the HTML element that registers the current event

<style>        ul {           background-color:red;        }        #wl {           background-color:blue;        }        a {           background-color:yellow;        }    </style>

6. Block default behavior

Do not use the default, but

<body><a href= "#" > Links </a><script>    var aelement = document.getelementsbyname (' a ');    /*aelement.addeventlistener (' click ', Function (event) {        event.preventdefault ();//block default behavior    }); *        / Aelement.onclick = function (event) {        event.preventdefault ();        return false;    }    Aelement.attachevent (' onclick ', function (event) {        var e = Event | | window.event;        E.returnvalue = false;    }) </script></body>

7. Get the mouse

Pagex and Pagey indicate relative to the page
Clientx and clienty represent visible areas
Screenx and Screeny represent the current screen in the

<body><script>    var html = document.documentelement;    Html.addeventlistener (' click ', Function (event) {        Console.log (Event.pagex, event.pagey);        Mouse coordinate values relative to the current HTML page        console.log (Event.clientx, event.clienty);        Mouse coordinate values relative to the current viewable area        Console.log (Event.screenx, event.screeny);        Mouse coordinate values        can only be obtained from//mouse coordinate values relative to the current screen, cannot be set    });</script></body>

8. Event Flow

<style> #q1 {width:200px;            height:200px;            background-color:red;        padding:50px;            } #q2 {width:100px;            height:100px;            Background-color:yellow;        padding:50px;            } #q3 {width:100px;            height:100px;        Background-color:blue; } </style>

9. Event Delegation

A large number of HTML elements register the same event, and the event handle logic is the same, causing the page speed to drop and the event stream to allow these HTML elements to register the event with the half-level element

<body><div id= "QH" > <button id= "qyc1" > Buttons </button> <button id= "qyc2" > button </button> <button id= "qyc3" > button </button></div><script> var q    YC1 = document.getElementById (' qyc1 ');    Qyc1.addeventlistener (' click ', Function () {Console.log (' This is a button ');    });    var qyc2 = document.getElementById (' qyc2 ');    Qyc2.addeventlistener (' click ', Function () {Console.log (' This is a button ');    });    var qyc3 = document.getElementById (' qyc3 ');    Qyc3.addeventlistener (' click ', Function () {Console.log (' This is a button ');    });        var QH = document.getElementById (' QH ');//Do not bind the event to the specified element, bind to the co-parent and ancestor element Qh.addeventlistener (' click ', Function (event) {        var target = event.target;//Trigger event Target element if (targe.nodename = = = ' button ') {Console.log (' This is a button '); }}) </script></body> 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.