JavaScript interacts with HTML--Events

Source: Internet
Author: User
Tags event listener

The interaction of JavaScript and HTML is implemented through events. JavaScript uses an asynchronous event-driven programming model that generates events when a document, browser, element, or related object occurs. If JavaScript is concerned with a particular type of event, it can register a handle to be invoked when such an event occurs.

Event Flow

Event flow describes the order of receiving events from the page, such as two nested div, click on the inner Div, this is the inner div first to start the Click event or the outer layer first trigger? There are currently three types of models

Event bubbling of IE: the event starts with the most specific element received, then propagates up to the less specific element

Netscape event capture: Less specific nodes receive events earlier, while most specific elements receive events last, and event bubbling is reversed

Dom Event Flow: The DOM2 level event specifies that the event flow consists of three stages, an event capture phase, a target phase, an event bubbling phase, an event capture, an opportunity to intercept an event, an actual target receiving an event, and finally a bubbling sentence phase.

Opera, Firefox, Chrome, Safari all support DOM event stream, IE does not support event flow, only supports event bubbling

If you have the following HTML, click the div area

<! DOCTYPE HTML >

Event bubbling Model

Event capture Model

Dom Event Flow

Event handlers (handler)

We also call it an event listener (listener), an event that is an action performed by the user or the browser itself. For example, click, Load, Moseover, etc. are event types (commonly known as event names), and the method in response to an event is called an event handler or event listener or event handle, and the event handler name is: on+ event type.

With this in view, let's look at how to add an event handler to an element

HTML Event handlers

Each event supported by an element can be specified using an HTML attribute with the same name as the corresponding event handler. The value of this property should be a JavaScript code that can be executed, and we can add the click event handler for a button

<input type= "button" value= "click here" onclick= "alert (' clicked! ');"/>

You can include specific actions to perform in an HTML event handler, or you can invoke a script defined elsewhere on the page, as the example can be written

<input type= "button" value= "click here" onclick= "showmessage ();"/>    <script type= "Text/javascript" >        function ShowMessage () {            alert (' clicked! ');        }

It is convenient to specify event handlers in HTML, but there are two drawbacks.

First, there is a load order problem, and if the event handler is loaded after the HTML code, the user may have a time lag problem when the event handler is not loaded and the trigger event is clicked.

Secondly, it is not convenient to write HTML code and JavaScript code tightly coupled.

JavaScript Specifies event handlers

Specifying an event handler through JavaScript is the event handler property that assigns a method to an element. Each element has its own event handler property, which is usually lowercase, such as onclick, and the value of these properties is set to a method, and the event handler can be specified as follows

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        Btnclick.onclick = function ShowMessage () {            alert (this.id);        };    </script>

In so doing, the event handler is considered the method of the element, the event handler runs under the scope of the element, and this is the current element, so clicking the button results in: Btnclick

This also has the advantage that we can delete the event handler by simply assigning the element's OnClick property to null

DOM2 Event handlers

The DOM2 level event defines two methods for handling the specified and deleted event handlers: AddEventListener and RemoveEventListener. All DOM nodes contain both methods, and they all accept three parameters: Event Type , event handling method, and Boolean value. The last Boolean parameter, if true , indicates that the event handler is called during the capture phase and, if false, is processed during the event bubbling phase .

We can write the example just now.

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        Btnclick.addeventlistener (' click ', Function () {            alert (this.id);        }, False);    </script>

The above code adds a handler for the Click event for the button, which is triggered during the bubbling phase, and, like the previous method, it runs under the scope of the element, but one benefit is that we can add multiple handlers for the Click event

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        Btnclick.addeventlistener (' click ', Function () {            alert (this.id);        }, False);        Btnclick.addeventlistener (' click ', Function () {            alert (' hello! ');        }, False);    </script>

This allows two event handlers to be executed in the order they were added after the user clicked a button.

The event handlers added via AddEventListener can only be removed by RemoveEventListener, and when the parameters are removed the same as when they were added, this means that the anonymous function we just added cannot be removed because the anonymous function is not the same as the method body, but the handle is not the same , so we can write this when we have the event handler removed.

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        var handler=function () {            alert (this.id);        }        Btnclick.addeventlistener (' Click ', Handler, false);        Btnclick.removeeventlistener (' Click ', Handler, false);    </script>

The following is the commonplace IE compatibility problem ...

IE does not support the AddEventListener and RemoveEventListener methods, but implements two similar methods Attachevent and DetachEvent, both of which receive two identical parameters, The event handler name and event handler method, because IE refers to support event bubbling, the added program is added to the bubbling phase.

Use Attachevent to add event handlers as follows

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        var handler=function () {            alert (this.id);        }        Btnclick.attachevent (
' OnClick '
, handler);    </script>

The result is undefined, it's strange, we'll introduce you in a moment

An event handler added with Attachevent can be removed by detachevent, and the condition is the same parameter, and the anonymous function cannot be removed.

<input id= "Btnclick" type= "button" value= "click here"/>    <script type= "Text/javascript" >        var Btnclick = document.getElementById (' Btnclick ');        var handler=function () {            alert (this.id);        }        Btnclick.attachevent (' onclick ', handler);        Btnclick.detachevent (' onclick ', handler);    </script>

Cross-browser event handlers

As we can see in the previous section, in different browsers, adding and removing event handlers is not the same, to write cross-browser event handlers, first we need to understand the different browser processing event handler differences

In adding event handlers things AddEventListener and attachevent have several major differences

1. The number of arguments is not the same, the most intuitive, AddEventListener has three parameters, attachevent only two, Attachevent added event handlers can only occur in the bubbling phase, AddEventListener The third parameter determines whether the added event handlers are processed during the capture or bubbling phase (we generally set the bubble stage for browser compatibility)

2. The first parameter is different in meaning, AddEventListener the first parameter is the event type (for example, Click,load), and attachevent the first parameter indicates the event handler name (Onclick,onload)

3. The scope of the event handler is not the same, the AddEventListener scope is the element itself, this is the trigger element, and the Attachevent event handler runs within the global variable, this is the window, So the example just returned undefined, not the element ID.

4. When adding multiple event handlers for an event, the order of execution is different, and the AddEventListener add is executed in the order of addition, while attachevent adds multiple event handlers in an irregular order (most of them are executed in the reverse order of the added order when the method is added). But add more is no rule, so add more time, do not rely on the order of execution Fortunately, if you rely on the function execution order, it is best to handle, do not expect the browser

After understanding the four-point difference, we can try to write a better browser-compatible Add event handler method

function addevent (node, type, handler) {            if (!node) return false;            if (node.addeventlistener) {                Node.addeventlistener (type, handler, false);                return true;            }            else if (node.attachevent) {                node.attachevent (' on ' + type, handler,);                return true;            }            return false;        }

In this way, first we solved the first problem parameter number is different, now three parameters, using event bubbling phase trigger, the second problem can also be resolved, if it is IE, we add the type on, the fourth problem currently has no solution, requires the user's own attention, under normal circumstances, People will not add a lot of event handlers, it feels good to try this method, but we did not solve the third problem, because the scope of the handler is different, if there is a handler within the same operation, then there will be an error in IE, most functions will actually have this operation.

function addevent (node, type, handler) {            if (!node) return false;            if (node.addeventlistener) {                Node.addeventlistener (type, handler, false);                return true;            }            else if (node.attachevent) {                node.attachevent (' on ' + type, function () {handler.apply (node);});                return true;            }            return false;        }

This can solve the problem of this, but the new problem again, we have to add an anonymous event handler, unable to cancel the event handler with DetachEvent, there are many solutions, we can learn from the master's approach, the founder of jquery that's what John Resig did.

function addevent (node, type, handler) {            if (!node) return false;            if (node.addeventlistener) {                Node.addeventlistener (type, handler, false);                return true;            }            else if (node.attachevent) {                node[' e ' + type + handler] = handler;                Node[type + Handler] = function () {                    node[' e ' + type + handler] (window.event);                };                Node.attachevent (' on ' + type, Node[type + handler]);                return true;            }            return false;        }

When the event handler is canceled

function removeevent (node, type, handler) {            if (!node) return false;            if (node.removeeventlistener) {                Node.removeeventlistener (type, handler, false);                return true;            }            else if (node.detachevent) {                node.detachevent (' on ' + type, Node[type + handler]);                Node[type + handler] = null;            }            return false;        }

John Resig A very clever use of closures and looks good.

Event Object

Triggering an event on the DOM produces an event object that contains all the information related to the event, including information about the element that generated the event, the type of event, and so on. Event objects are supported for all browsing, but are supported in different ways.

Event objects in the DOM

A DOM-compatible browser produces an event object in an incoming events handler. Apply the Addevent method we wrote just now.

var Btnclick = document.getElementById (' Btnclick ');    Addevent (Btnclick, ' click ', handler);

When we click on the button, we can see that the popup is the click Pop-up window.

The Event object contains properties and methods related to the specific event that created it, different types of triggering events, and the available properties and methods are different, but all events will contain

Properties/Methods

Type

Read/write

Description

Bubbles Boolean Read-only Whether the event bubbles
Cancelable Boolean Read-only Whether the default behavior of an event can be canceled
Currenttarget Element Read-only event handler currently processing element
Detail Integer Read-only Details about the event
Eventphase Integer Read-only Event handler phase: 1 Capture phase, 2 in Target stage, 3 bubbling Stage
Preventdefault () Function Read-only Cancel event default behavior
Stoppropagation () Function Read-only Cancel event further capture or bubbling
Target Element Read-only The target element of the event
Type String Read-only The type of event being triggered
View Abstractview Read-only The abstract view associated with the event, equivalent to the Window object where the event occurred

Within an event handler, this is always the same as currenttarget, and target is the actual target of the event.

To block the default behavior of an event, you can use the Preventdefault () method, provided that the cancelable value is true, such as we can block the default behavior of link navigation

document.getElementsByTagName (' a '). onclick = function (e) {            e.preventdefault ();        }

The Stoppaopagation () method stops the event from propagating at the DOM level, which is to cancel further event capture or bubbling. We can call Stoppropagation () in the event handler of the button to avoid events that are registered on the body

var handler = function (e) {            alert (e.type);            E.stoppropagation ();        }        Addevent (document.body, ' click ', function () {alert (' Clicked Body ')});        var Btnclick = document.getElementById (' Btnclick ');        Addevent (Btnclick, ' click ', handler);

If you comment out e.stoppropagation (); When the button is clicked, the body's Click event is also triggered by the event bubbling, but the event stops propagating after this sentence is invoked.

Event objects in IE

There are several different ways to access an event object in IE, depending on how you specify the event handler. When you add an event handler directly for a DOM element, the event object exists as a property of the Window object

var handler = function () {            var e = window.event;            alert (e.type);        }        var Btnclick = document.getElementById (' Btnclick ');        Btnclick.onclick = handler;

We obtained the event object through window.event and detected its type, but if the event handler was added through Attachevent, then there will be an event object being passed into the handler

var handler = function (e) {            alert (e.type);        }        var Btnclick = document.getElementById (' Btnclick ');        Attachevent (Btnclick, handler);

Of course, this time can also be accessed through the Window object to the event, for convenience, we usually pass in the event object, ie all events contain the following attribute methods

Properties/Methods

Type

Read/write

Description

Cancelbulle Boolean Read/write The default is false, which can be canceled when event bubbling is set to True
ReturnValue Boolean Read/write Default is True, set to False to cancel the event default behavior
Srcelement Element Read-only The target element of the event
Type String Read-only The type of event being triggered
Cross-browser Event objects

Although Dom and IE have different event objects, we can write cross-browser event object scenarios based on their similarity.

function GetEvent (e) {            return e | | window.event;        }        function Gettarget (e) {            return e.target | | e.screlement;        }        function Preventdefault (e) {            if (e.preventdefault)                e.preventdefault ();            else                e.returnvalue = false;        }        function Stoppropagation (e) {            if (e.stoppropagation)                e.stoppropagation ();            else                e.cancelbubble = true;        }

Common HTML Events

There are some HTML events we will often use, these events are not necessarily related to user action, here is simply mentioned, detailed usage everyone has Baidu Google

    1. Load: Triggered on the window when the page is fully loaded, triggered on an IMG element when the image is loaded, or triggered on an object element when the embedded content is loaded
    2. Unload: Triggered on a window after a page is completely unloaded, or when embedded content is unloaded on an object element
    3. Select: triggered when the user selects a character in a text box
    4. Change: Triggers when the value of a text box changes after it has changed focus
    5. Submit: Triggered when the user submits the form
    6. Resize: triggers when window or frame size changes on windows
    7. Scrool: When a user scrolls an element with a scrollbar, it fires on that element
    8. Focus: Triggers on window and corresponding elements when the page or element receives focus
    9. Blur: Triggers on window and corresponding element when the page or element loses focus
    10. Beforeunload: Trigger on window before page unload
    11. MouseWheel: Not HTML, triggered when the user interacts with the page through the mouse wheel and scrolls the page vertically

JavaScript interacts with HTML--Events

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.