Events that JavaScript must learn every day, javascript events

Source: Internet
Author: User

Events that JavaScript must learn every day, javascript events

In fact, this article was written quite early. However, due to the bug in sf storage, I wrote a lot and the results were not saved. I think it is a great pity that I did not finish writing this article, today, I just gave it a try, and I just made an end article for my javascript learning summary.

Here, we will mainly discuss js-related events --

Event Handler 

Some events are defined in the DOM, and functions that respond to an event are called event handlers (or event listeners ). The name of the event handler generally starts with "on", for example, onclick.

Event bubbling and capture 

Event stream refers to the order in which events are received on the page. IE, Firefox, and chrome are both event bubbles. Event bubbles refer to events first received by the most specific elements, then, the nodes are gradually propagated to unspecified nodes. Event capturing is the opposite. Event capturing is proposed by Netscape. Event bubbling and capturing are as follows:

 

Although event capture is the only event stream model supported by Netscape, both Firefox and Google currently support this event stream model.

Benefits of event bubbling

Because the event has a bubble mechanism, we can use the bubble principle to add the event to the parent level to trigger the execution effect. The benefit of doing so is, of course, improving performance,

 

In this way, we can add a mouse event on the li. However, if we say there may be many li for loops, the performance will be affected.

We can use event delegation to achieve this effect. Html unchanged:

<Script type = "text/javascript"> window. onload = function () {var aUl = document. getElementsById ("bubble"); var aLi = aUl. getElementsByTagName ("li"); // no matter which event you are operating on, the element is the event source. // Ie: window. event. srcElement // standard: event.tar get aUl. onmouseover = function (ev) {var ev = ev | window. event; var target = ev.tar get | ev. srcElement; if (target. nodeName. toLowerCase () = "li") {target. style. background = "blue" ;}}; aUl. onmouseout = function (ev) {var ev = ev | window. event; var target = ev.tar get | ev. srcElement; if (target. nodeName. toLowerCase () = "li") {target. style. background = "" ;}}}; </script>

So, how can we prevent event bubbles? Let's look at the following example:

<Div onclick = "showMsg (this, event)" id = "outSide" style = "width: 100px; height: 100px; background: #000; padding: 50px "> <div onclick =" showMsg (this, event) "id =" inSide "style =" width: 100px; height: 100px; background: # CCC "> </div> <script type =" text/javascript "> // After blocking event bubbling, click the gray box, the entire process is only one dialog box (note the comparison with the default situation) function showMsg (obj, e) {alert (obj. id); stopBubble (e)} // function of the event prevention bubble function stopBubble (e) {if (e & e. stopPropagation) e. stopPropagation () else window. event. cancelBubble = true} </script>

Click the black perimeter:

 

DOM 0-level event handler 

Specifying an event handler through js usually assigns the callback function to the attributes of the event handler. Each element has its own event handler attribute (the attribute is in lowercase, for example, onclick)

 btn.onclick = function(){ console.log('hello');}; 

Using the event handler specified by DOM level 0 is considered an element method. Therefore, this points to the current element:

Var btn = document. getElementById ('mydiv '); // events triggered on the DOM will generate an event object eventbtn. onclick = function (event) {alert (this. id); // myDiv };

DOM level 1

DOM level 1 focuses on HTML and XML document models. It provides document navigation and processing functions.

DOM level 1 became W3C recommendation standard in October 1, 1998.

The second draft of work was held in September 29, 2000.

It is worth mentioning that DOM level 0 is not a W3C standard. It is just a definition of the equivalent functionality in Netscape Navigator 3.0 and IE 3.0.

DOM Level 2 event handler 

DOM 2 defines two methods for specifying and deleting Event Handlers: addEventListener () and removeEventListener (). They both accept three parameters:

1. event name. For example, click
2. functions used as event handlers.
3. boolean value (true indicates that the event handler is called in the capture phase, and false indicates the bubble phase)

You can use the addEventListener method of the Element object to define the Event Callback Function.

 //element.addEventListener(event, function, useCapture)var btn = document.getElementById('myDiv');btn.addEventListener('click', function () { console.log(this.id);},false); 

Event handler in IE 

The IE browser before IE9 does not support addEventListener () and removeEventListener ().

Different from other browsers, IE uses the attachEvent () and detachEvent () Methods to add event handlers to the DOM. Since IE8 and earlier versions only support event bubbling, therefore, they only accept two parameters:
1. event handler name (on must be added before)
2. event handler Functions
The event handler added using attachEvent () is as follows:

 var btn = document.getElementById('myDiv');btn.attachEvent('onclick', function () { console.log(this.id);}); 

It is worth noting that when the attachEvent () method is used, the event handler will run in the global scope. Therefore, this equals to window

Event object
 
When an event on the DOM is triggered, an event object is generated, which contains all event-related information. Includes the elements that cause the event, the event type, and other information related to the specific event. The event object will be passed to the callback function of the event listener as the first parameter. We can use this event object to obtain a large amount of information related to the current event:
Type (String)-event name
Target (node)-DOM node of event Origin
CurrentTarget? (Node)-DOM node triggered by the current callback function (More details will be provided later)
Bubbles (boolean)-specifies whether the event is a bubble event (which will be explained later)
PreventDefault (function)-This method will prevent the browser's user agent from triggering the default behavior of the current event. For example, you can prevent the click event of <a> element from loading a new page.
Cancelable (boolean)-This variable indicates whether the default behavior of this event can be blocked by calling event. preventDefault.
StopPropagation (function)-cancel further event capture or bubbling. Use this method if bubbles is true.
EventPhase: returns a number indicating the current stage of the event. 0 indicates that the event starts to spread from the DOM surface to the target element. 1 indicates the capture stage, and 2 indicates that the event reaches the target element, 3 is the bubble stage.

In addition, event objects may have many other attributes, but they are all for specific events. For example, a mouse event contains the clientX and clientY attributes to indicate the cursor position in the current window.

In addition, the stopPropagation () method is used to stop the propagation of an event in the DOM immediately, that is, to cancel further event bubbling or capturing.

Var btn = document. getElementById ('mydiv '); btn. onclick = function (event) {alert ("clicked"); event. stopPropagation () ;}; // avoid triggering in document. the event handler document on the body. body. onclick = function (event) {alert ("Body clicked ");};

The event object exists only when the event handler is executed. Once the event handler is executed, the event object is automatically destroyed.

Event object in IE

When an event handler is added to DOM level 0, the event object exists as an attribute of the window object:

 var btn = document.getElementById('myDiv');btn.onclick = function (event) { var event = window.event; alert(event.type);//click}; 

The event object of IE also contains the attributes and methods related to the events created for it.
The default value of cancleBubble is false, but can be set to true to cancel event bubbling, which is the same as the stopPropagation () method in dom.
The default value of the returnValue Boolean is true. When it is set to false, the default behavior used to cancel the event is the same as the preventDefault () in the dom.
The target of the srcElement element event, which is the same as the target attribute in the dom.
The type of the event triggered by the string.

Click Event

After a user clicks, the event object will contain the following attributes.
PageX, pageY: the coordinate of the click position relative to the html element, in pixels.
ClientX and clientY: coordinates of the click position relative to the viewport, in pixels.
ScreenX and screenY: the coordinates of the click position relative to the display screen of the device, measured in pixels of hardware.

ClientX, clientY

Illustration: clientX and clientY. Their values indicate the horizontal and vertical coordinates of the mouse pointer in the viewport when an event occurs (excluding the scroll bar area)

Offset

You can use the following four attributes to get the offset of an element.

(1) offsetHeight: the space occupied by the element in the vertical direction, in pixels. It includes the height of the element, the height of the (visible) horizontal scroll bar, the height of the top border, and the height of the bottom border.

(2) offsetWidth: the space occupied by the element in the horizontal direction, in pixels. It includes the width of the element, the width of the (visible) vertical scroll bar, the width of the left border, and the width of the right border.

(3) offsetLeft: The pixel distance between the left outer border of the element and the left inner border of the element.

(4) offsetTop: The pixel distance between the upper and outer borders of an element and the upper and middle borders of an element.

PageX, pageY

These two attributes indicate the position of the mouse cursor in the page. If the page does not scroll, The pageX and pageY values are equal to those of clientX and clientY.

Scroll size

The scroll size refers to the size of elements that contain the scrolling content.

The following are four attributes related to the scroll size.

(1) scrollHeight: the total height of the element content without a scroll bar.

(2) scrollWidth: The total width of the element content without a scroll bar.

(3) scrollLeft: number of records hidden on the left of the content area. You can set this attribute to change the scrolling position of an element.

(4) scrollTop: number of records hidden above the content area. You can set this attribute to change the scrolling position of an element.

Focus event

A focus event is triggered when the page element gets or loses focus. There are four focus events:
1. blur: triggered when the element loses focus. This event is not bubbling.
2. focus: triggered when the element obtains the focus. Do not bubble
3. focusin: triggered when the element obtains the focus. It is bubbling.
4. focusout: triggered when the element loses its focus. It is bubbling.

Mouse events

DOM 3 defines nine mouse events:
Click: It is triggered when you click the primary key of the mouse or press the Enter key.

Dbclick: triggered when you double-click the mouse.

Mousedown: When you press any mouse key, this event cannot be triggered by the keyboard.

Mousemove: this event is repeatedly triggered when the mouse moves around an element. It cannot be triggered by a keyboard event.

Mouseout: triggered when the mouse leaves the element. This event cannot be triggered by the keyboard.

Mouseover: triggered when the mouse enters the element. This event cannot be triggered by the keyboard.

Mouseenter: it is similar to "mouseover", but does not bubble, and will not be triggered when the cursor moves to the child element.

Mouseleave: similar to "mouseout", but not bubbling. It is not triggered at the top of the element.

Mouseup: triggered when the user releases the mouse button. It cannot be triggered through the keyboard.

The event objects passed to the mouse event handler have the clientX and clientY attributes, which specify the coordinates of the mouse pointer relative to the containing window. By adding the scroll offset of the window, you can convert the mouse position to the document coordinate.
All elements on the page support mouse events. All events except mouseenter and mouseleave are bubbling and Their default behaviors can be canceled. However, canceling default mouse events may affect other events, because some mouse events are mutually dependent.

Drag events 

(1) drag event
The drag event is triggered when the source object is dragged.
(2) dragstart and dragend events
The dragstart event is triggered when the user starts to drag an object with the mouse, and the dragend event is triggered when the drag ends.
(3) dragenter and dragleave events
The dragenter event is triggered on the target object after the source object is dragged into the target object. The dragleave event is triggered on the target object after the source object leaves the target object.
(4) dragover event
The dragover event is triggered when the source object is dragged over another object.
(5) drop event

When the source object is dragged to the top of the target object, the drop event is triggered on the target object when you release the mouse.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.