Event handler in javascript

Source: Internet
Author: User

 

I recently read the book "javascript advanced program" and write my own experiences with caution. I hope you can get some guidance and discussion from the ox.

 

Today's question is: javascript event processing functions. We know that interaction between javascript and HTML is implemented through events. Events are actions performed by users or browsers, for example, click, mounseover, load ......, The function that responds to an event is called an event processing function (or an event listener ).

 

Event handler in HTML code:

View sourceprint? 1 <input type = "button" value = "click me" onclick = "alert ('clickme')"/>

 

Here, we directly inline the event handler into the HTML code, but this is extremely unfriendly for us to read the code. Below we separate the event handler, as shown below:

 

View sourceprint? 1 function showMessage (){

 

2 alert ("click me ");

 

3}

 

 

Then we call the following in the HTML code:

 

View sourceprint? 1 <input type = "button" value = "click me" onclick = "showMessage ()"/>

 

Specifying event processing functions in HTML has two disadvantages:

 

1. there is a time difference. In the preceding example, assume that the showMessage () function is defined at the bottom of the page. If you click the button before parsing the showMessage () function, this will cause errors. For this reason, many HTML event processing functions are closed in the try-catch Block, so that the error will not be exposed, as shown below:

 

View sourceprint? 1 <input type = "button" value = "click me" onclick = "try {showMessage ()} catch (e) {}"/>

 

2. the HTML code is closely coupled with the javascript code. to update the event processing function, you need to update the two locations. Because of these two problems, we generally seldom use this event processing method in actual work.

 

DOM0-level event handler:

View sourceprint? 1 var btn = document. getElementById ("myBtn ");

 

2 btn. onclick = function (){

 

3 alert ("clicked! ");

 

4}

 

Assign a function to the attribute of an event handler. Since this method is currently supported by all browsers, it is easy to use and cross-browser! The event handler specified by the DOM0-level method is considered an element method. At this time, the event runs in the element scope, that is, this in the program references the current element.

 

You can also delete the event handler specified by the DOM0-level method, as shown below:

 

View sourceprint? 1 btn. onclick = null;

 

DOM2-level event handler:

DOM2 events define two methods: addEventListener () and removeEventListener ()

 

To add an event handler for the click button, use the following code:

 

View sourceprint? 1 var btn = document. getElementById ("myBtn ");

 

2 btn. addEventListener ("click", function (){

 

3 alert (this. id );

 

4}, false );

 

Because the third parameter is false, the event is triggered in the bubble stage. The advantage of using a DOM2-level event handler is that multiple event handlers can be added.

 

We can also remove the Event Handler through removeEventListener (), as shown below:

 

View sourceprint? 1 var btn = document. getElementById ("myBtn ");

 

2 btn. removeEventListener ("click", function (){

 

3 alert (this. id );

 

4}, false );

 

IE event handler

IE implements two methods similar to DOM, attachEvent and deatachEvent (), as shown in the following code:

 

View sourceprint? 1 var btn = document. getElementById ("myBtn ");

 

2 btn. attachEvent ("click", function (){

 

3 alert (this. id );

 

4 });

 

5

 

6 var btn = document. getElementById ("myBtn ");

 

7 btn. detachEvent ("click", function (){

 

8 alert (this. id );

 

9 });

 

Cross-browser Event Handlers:

Because the DOM2-level event handler is different from the event handler in IE, we may use the capability to detect the unified event handler, as shown in the following code:

 

View sourceprint? 01 var eventUtil = {

 

02 addListener: function (element, type, hander ){

 

03 if (element. addEventListener ){

 

04 element. addEventListener (type, hander, false );

 

05} else if (element. attachEvent ){

 

06 element. attachEvent ('on' + type, hander );

 

07} else {

 

08 element ['on' + type] = hander;

 

09}

 

10 },

 

11

 

12 removeListener: function (element, type, hander ){

 

13 if (element. removeEventListener ){

 

14 element. removeEventListener (type, hander, false );

 

15} else if (element. deattachEvent ){

 

16 element. detachEvent (type, hander );

 

17} else {

 

18 element ['on' + type] = null;

 

19}

 

20 },

 

21 };

 

Event objects in DOM:

A dom-compatible browser will have an event object passed into the event handler. No matter what method is used in the specified event handler, the event object will be passed in, the attributes and methods of common event objects include:

 

1. currentTarget: the element whose event handler is currently processing the event;

2. target: The Event target;

3. preventDefault (): cancels the default event behavior;

4. stopPropagation (): cancels the event to further capture and bubble.

 

Event objects in IE:

Like the event object in DOM, the event object in IE also has the above attributes or methods, but the implementation is somewhat different. The following is the correspondence between them:

 

1. srcElement <=> target;

2. returnValue = false <=> preventDefault ();

3. cancelBubble = true <=> stopPropagation ();

 

Cross-browser event objects:

Because the event objects in DOM are different from those in IE, we can also use the capability detection method to unify the attributes and Methods Commonly Used in event objects (eventUtil. js ):

 

View sourceprint? 01 var eventUtil = {

 

02 addListener: function (element, type, hander ){

 

03 if (element. addEventListener ){

 

04 element. addEventListener (type, hander, false );

 

05} else if (element. attachEvent ){

 

06 element. attachEvent ('on' + type, hander );

 

07} else {

 

08 element ['on' + type] = hander;

 

09}

 

10 },

 

11

 

12 getEvent: function (event ){

 

13 return event | window. event;

 

14 // return event? Event: window. event;

 

15 },

 

16

 

17 getTarget: function (event ){

 

18 return event.tar get | event. srcElement;

 

19 },

 

20

 

21 preventDefault: function (event ){

 

22 if (event. preventDefault ){

 

23 event. preventDefault ();

 

24} else {

 

25 event. returnValue = false;

 

26}

 

27 },

 

28

 

29 removeListener: function (element, type, hander ){

 

30 if (element. removeEventListener ){

 

31 element. removeEventListener (type, hander, false );

 

32} else if (element. deattachEvent ){

 

33 element. detachEvent (type, hander );

 

34} else {

 

35 element ['on' + type] = null;

 

36}

 

37 },

 

38

 

39 stopPropagation: function (event ){

 

40 if (event. stopPropagation ){

 

41 event. stopPropagation ();

 

42} else {

 

43 event. cancelBubble = true;

 

44}

 

45}

 

46 };

 

Finally, we can use a simple example to demonstrate how to use a custom eventUtil object. The complete sample code is as follows:

 

View sourceprint? 01

 

02

 

03 <title> event util test </title>

 

04 <script type = "text/javascript" src = "eventUtil. js"> </script>

 

05

 

06 <body>

 

07 <a href = "http://www.baidu.com"> baidu </a>

 

08 <script type = "text/javascript">

 

09 (function (){

 

10 var btn = document. getElementById ("btn ");

 

11 var link = document. getElementsByTagName ("a") [0];

 

12 eventUtil. addListener (link, "click", function (event ){

 

13 alert ("prevent default event ");

 

14 var event = eventUtil. getEvent (event );

 

15 eventUtil. preventDefault (event );

 

16 });

 

17

 

18 eventUtil. addListener (btn, "click", function (event ){

 

19 var event = eventUtil. getEvent (event );

 

20 var target = eventUtil. getTarget (event );

 

21 alert (event. type );

 

22 alert (target );

 

23 eventUtil. stopPropagation (event );

 

24 });

 

25

 

26 eventUtil. addListener (document. body, "click", function (){

 

27 alert ("click body ");

 

28 });

 

29 })();

 

30 </script>

 

31 </body>

 

32

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.