jquery Event and Event object Introductory Learning Tutorial

Source: Internet
Author: User
Tags anonymous documentation html tags

Event and Event objects

First look at the ways in which you add events that we often use:
  code is as follows copy code
<script type= "Text/javascript" src= "Scripts/jquery-1.3.2-vsdoc2.js" ></SCRIPT> 
 <script Type= "Text/javascript" > $ (function () {document.getElementById ("TestDiv2"). onclick = Showms
        }) function ShowMsg (event) {alert ("!!!"); } </script>  
 <div id= "TestDiv1 onclick=" showmsg (); " 
   > Click event 1</div> 
 <div id= "TestDiv2" > Click event 2</div> </body>  

We most often add events by adding onclick element attributes to an element.
The way to add an onclick event for TestDiv2 is to modify the DOM properties.

In the previous chapter, we explained what an element attribute is and what is a DOM property. The two methods have the same effect. A prompt box appears when you click a div.

Note that although the effect is the same, it is not equivalent.

The code is as follows Copy Code
document.getElementById ("TestDiv2"). onclick = showmsg;

is equivalent to:
<div id= "TestDiv1" onclick= "alert" ("!!!"); " > Click event 1</div>

Notice the difference between the two? The way we often modify element attributes to add events is actually to create an anonymous function:
The code is as follows Copy Code
document.getElementById ("TestDiv1"). onclick = function (event)
    alert ("!!!");

The signature of this anonymous function is the same as our handwritten showmsg signature, so we can assign the showmsg directly to the onclick.
The drawbacks of this approach are:
1. Only one event handler function can be bound for one event. Using the ' = ' assignment will flush out all the event handlers that were previously bound for this time.
2. The way to get event objects in an event function, whether it is an anonymous function or a bound function, is handled differently in different browsers:
In IE, the event object is a property of the Window object. The event handler must access the event object like this:
The code is as follows Copy Code
Obj.onclick=function () {var oevent = window.event;}
In the DOM standard, an event object must be passed as a unique parameter to the event handler function:
Obj.onclick=function ()
            var oevent = arguments[0];
In addition to using argument[0] to access this parameter, we can also specify the parameter name, which is equivalent to the following code:
The code is as follows Copy Code
Obj.onclick=function (oevent) {}
Pre-compatible DOM browsers have firefox,safari,opera,ie7 and so on.
3. Functions that add multicast delegates are not the same in different browsers.
The following are the available methods for adding multicast delegates that are compatible with multiple browsers:
Unified method for adding multicast event delegates to an object/*       parameter description:     otarget     :
The object to add the event to. such as "document".     Seventtype  : Event type. For example Click event
"Click".     Fnhandler   : The method that is invoked when an event occurs. For example, a static function "Hidecalendar"
Use example:     //Click on any element of the page to close the Calendar control as long as no bubbling is canceled
  code is as follows copy code
  code is as follows copy code
 var CF = document.getElementById ("Calframe"); 
 if (cf!= null && hidecalendar!= null) {
 Scripthelper.addeventlistener (document, click, h     Idecalendar); } 
 */scriptHelper.prototype.addEventListener = function (Otarget, Seventtype, Fnhandler) {if (Otarget.addev Entlistener)//for dom {Otarget.addeventlistener (Seventtype, Fnhandler, False)} else if (otarget.a
    ttachevent)//for ie {otarget.attachevent ("on" + Seventtype, Fnhandler); }
So we should first abandon &lt;div onclick= "..." &gt;&lt;/div&gt; the way to add events by modifying element attributes. Try to bind multiple event handlers for an event by adding multicast event delegates, such as adding a method to close the pop-up layer for a Document object's Click event, and using multicast does not affect the original event handler function of the Document object.

Four. Events in jquery

With jquery, we have a series of functions that handle object events.  The basics are still understood, but you don't have to implement the function of handling multicast event delegates. There is the so-called jquery, drink tea every day water. Here are some examples of the bind () method that is most commonly used in jquery:

The code is as follows Copy Code
$ ("#testDiv4"). Bind ("click", ShowMsg);

We add the event handler function showmsg for the column click event for the element that ID is testDiv4.
Benefits of using the JQuery event handler function:
1. A multicast event delegate is added. That is, adding a method for the Click event does not overwrite the original event handler for the object's Click event.
The code is as follows Copy Code
$ ("#testDiv4"). Bind ("click", Function (event) {alert ("one");});
            $ ("#testDiv4"). Bind ("click", Function (event) {alert ("two");});

When you click the TestDiv4 object, you are prompted "one" and "two" in turn.
2. Unified the event name.
When you add a multicast event delegate, the event name in IE is preceded by "on". But using the bind () function we don't have to distinguish between IE and DOM, because internal jquery has helped us unify the name of the event.
3. You can control the object's behavior in all scripts.
Let the HTML code section notice only the "show" logic. The trend now is to cut the behavior, content and style of the HTML cleanly. It uses script to control element behavior, control element content with HTML tag, control element style with CSS. You can avoid adding events directly to HTML tags by using the jquery event handler function.
The following is the underlying jquery event handler function:
Event handler handling:
Name Description Example
Bind (type, [data], FN)
Bind an event handler function to a specific event (like click) for each matching element. When each paragraph is clicked, the text pops up:
$ ("P"). Bind ("click", Function () {
Alert ($ (this). text ());
One (type, [data], FN) Bind a one-time event handler for each matching element's specific event (like click). When all the paragraphs are clicked for the first time, display all their text:
$ ("P"). One ("click", Function () {
Alert ($ (this). text ());
Trigger (event, [data]) Triggers a class of events on each matching element.
This function also causes the default behavior of the browser to be executed with the same name. For example, if you use trigger () to trigger a ' submit ', the same will cause the browser to submit the form. If you want to block this default behavior, you should return false.
You can also trigger the custom event registered by bind ()
To pass an argument to an event:

$ ("P"). Click (Function (event, a, b) {
An ordinary click event, A and B are undefined types
If triggered with the following statement, then a points to "Foo" and B points to "bar".
}). Trigger ("click", ["foo", "Bar"]);
Triggerhandler (event, [data]) does not perform browser default actions.
$ ("#old") . Click (function () {
  $ ("input"). Trigger ("focus");
$ ("#new"). Click (function () {
  $ ("input"). Triggerhandler ("Focus");
$ ("input"). focus (function () {   $ (' <span>Focused!</span> '). Appendto ("Body"). Fadeout ( 1000); });
Unbind (Type, fn) A reverse operation of BIND (), which deletes the bound event from each matching element.

If there are no parameters, all bound events are deleted.
You can unbind the custom event you registered with BIND ().
If the event type is provided as a parameter, only the binding event of that type is deleted.
If the handler function passed at binding is used as the second argument, only this particular event handler is deleted.
Unbind all events from all paragraphs:
$ ("P"). Unbind ()

Unbind the Click event of a paragraph:
$ ("P"). Unbind ("click")

Deletes the binding of a particular function, passing the function as a second argument:
var foo = function () {
Code to handle an event
$ ("P"). Bind ("click", foo); // ... When you click on the paragraph, it triggers Foo
$ ("P"). Unbind ("click", foo); // ... Will never be triggered Foo

Five. Examples of common event functions

1.bind (type, [data], FN) function Example

Bind () is the most commonly used function, note the data parameter on the method signature, and you can pass some additional data before the event is processed:
function Handler (event) {
  alert (event.data.foo);
$ ("P"). Bind ("click", {foo: "Bar"}, Handler)

Note the use of the event parameter. The event object is unified in jquery, and the event object is passed as the unique parameter of the event handler function.
The data parameters are also accessed through Event.data. Why do I have to supply the data parameter?
Because we often have this problem: you want special handling in event processing based on some data from the source of the event.
At present there are two kinds of dispute resolution methods on the Internet:
(1) Use custom element attributes to store data.
Like what:
<div id= "TESTDIV5" customer= "Customer Data 1" > Get Custom Data -1</div>

To get the data in the event handler function:
$ ("#testDiv5"). Bind ("click", Function (event) {alert ($ (event.target). attr ("Customer"));

The attr function is the knowledge in the previous lecture, which is used to get the element attributes of the elements, and to get the custom element properties. When you click the Div, it appears:
(2) using a script to pass data to an event handler function:
<div id= "TestDiv6" > Get Custom Data -2</div>

element does not have any custom attributes, and additional data is passed when the event handler is added:
$ ("#testDiv6"). Bind ("click", {customer: "Customer Data 2"}, function (event) {alert (Event.data.customer)});

Click the div after the results and Method 1 the same:
Method 1 makes it easy to store and find data. However, custom properties are validated by the non-domain.
Method 2 You have to find ways to store your data, and you need to make rules to find the data for the specified element.
Approach 1 from the developer perspective is simpler and more intuitive. But the disadvantages are rather serious. So how to make a choice for everyone to decide.
One (type, [data], FN) function is the same as bind, but only once.
2. trigger (event, [data]) and Triggerhandler (event, [data])
Although some events are bound for an element, such as click, but sometimes you want to trigger these events in your program, these two functions can implement this functionality.
The main difference is that trigger will start the browser default action, and Triggerhandler will not start.
These two functions are clearly distinguished by the following example:
&lt;! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" &nbsp; "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "&gt; &lt;html xmlns=" http://www.w3.org/1999/xhtml "&gt; &lt;head&gt; &lt;title&gt; jquery event handling: Trigger and Triggerhandler samples &lt;/title&gt; &lt;script type= "Text/javascript" src=
            Jquery-1.3.2-vsdoc2.js "&gt;&lt;/script&gt; &lt;script type=" Text/javascript "&gt; $ (function () {
                $ ("#old"). Click (function () {$ ("#divResult"). HTML ("");
            $ ("input"). Trigger ("focus");
                $ ("#new"). Click (function () {$ ("#divResult"). HTML ("");
            $ ("input"). Triggerhandler ("Focus");
        $ ("input"). focus (function () {$ ("&lt;span&gt;Focused!&lt;/span&gt;"). Appendto ("#divResult");}); }) &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button id= "old" &gt;. Trigger ("Focus") &lt;/butto N&gt; &Lt;button id= "New" &gt; Triggerhandler ("Focus") &lt;/button&gt;&lt;br/&gt; &lt;br/&gt; &lt;input type= "Te XT "Value=" to be focused "/&gt; &lt;div id=" Divresult "&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;

When you click the ". Trigger" button, the focesed is called two times, and the input element gets the focus:
When you click the. Triggerhandler button, you call only once, and the input element does not have the focus:
That is, the trigger function sets out the browser's default to get focus behavior, so that the input element gets the focus, so it calls the focused event handler again.
Triggerhandler only invokes event handlers that are bound for the focus event, but does not raise browser behavior, so the last INPUT element does not have the focal point.
Six. Shortcut event Helpers
Bug Tip: Jquery-1.3.2-vsdoc2.js This latest official class library with smart tips, you can't use shortcut events, such as Click (), focus (). There is no problem using a different version of the class library.
Although we can use event handlers to do almost all of the object's events, jquery provides encapsulation of common events. For example, click the two methods that correspond to the event, click (), and click (FN) to trigger the clicked event and set the Click event respectively.
To set the Click event:
$ ("#testDiv"). Click (Function (event) {alert ("Test div clicked!");

is equivalent to:
$ ("#testDiv"). Bind ("click", Function (event) {alert ("Test div clicked!");
Trigger Click event:
$ ("#testDiv"). Click ();

is equivalent to
$ ("#testDiv"). Trigger ("click");
Note that this is equivalent to trigger rather than triggerhandler.
This kind of method in jquery in English is called the event Helpers, I cannot find the very good translation way, therefore according to the function called it "the Quick Method", the collection good translation name!
The following is a list of the shortcut methods for jquery:
Since all are the corresponding events, so no longer write the description and examples.
Name Description Example
Blur ()
Blur (FN)
Change ()
Change (FN)
Click ()
Click (FN)
DblClick ()
DblClick (FN)
Error ()
Error (FN)
Focus ()
Focus (FN)
KeyDown ()
KeyDown (FN)
KeyPress ()
KeyPress (FN)
KeyUp ()
KeyUp (FN)
Load (FN)
MouseDown (FN)
MouseEnter (FN)
MouseLeave (FN)
MouseMove (FN)
Mouseout (FN)
MouseOver (FN)
MouseUp (FN)
Resize (FN)
Scroll (FN)
Select ()
Select (FN)
Submit ()
Submit (FN)
Unload (FN)
Seven. Interactive Help method
In addition to basic practice, jquery provides two and event-related help methods: hover (over, out) and toggle (FN, fn2, Fn3,fn4,...)
1. hover (over, out)
The hover function mainly solves the problem of mouseover and mouseout functions in primitive JavaScript, and look at the following example:
There are two div (red area), which has nested a div (yellow area). The HTML code is as follows:
<div class= "outer" id= "outer1" >       outer 1
      <div class= "inner" id= "Inner1" >inner     1</div> </div>     <div class= "outer" id= "outer2" >       outer 2
      <div class= "inner" id= "Inner2" >inner 2 </div>     </div>     <div id= "Console" ></div>
Bind to the following events:
<script type= "Text/javascript" >       function (Event) {
        $ (' #console '). Append (' <div> ' + Event.type+ ' </div> ');

      $ (function () {
        $ (' #outer1 ')
         . bind (' MouseOver ', the)
         . bind (' mouseout ', the);
        $ (' #outer2 '). Hover (Report,report);

Outer1 we used the mouseover and mouseout events, and when the mouse moved from the red area of Outer1 to the yellow area, it found that although it was moving inside the outer1, it triggered the Mouseout event:
Most of the time we do not want the results of the above image, but we want only the mouse to move inside the Outer1 does not trigger the event, Outer2 use the hover () function to achieve this effect:
Note that the event name here goes into "MouseEnter", leaving the term "mouseleave" instead of "mouseover" and "MouseLeave" events.
Experienced developers will immediately think of the creation of pop-up menus, often encountered this problem: the pop-up menu set the Mouseout event automatically shut down, but the mouse in the pop-up menu moves often inexplicably trigger the Mouseout event to shut down the menu. The hover () function helps us to solve the problem well.
2. Toggle (FN, fn2, Fn3,fn4,...)
The toggle function can add the Click event binding function for an object, but sets the call function sequentially after each click.
If a matching element is clicked, the first specified function is triggered, and when the same element is clicked again, the specified second function is triggered, and if there are more functions, it is triggered again until the last one. Successive calls to these functions are repeated for each subsequent click.
You can use Unbind ("click") to delete.
The following example shows how to use the Toggle function:
&lt;!     DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" &gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;toggle example&lt;/title&gt; &lt;link rel= "stylesheet" type= "Text/css" href= "Css/hover.css" &gt; &lt;s Cript type= "Text/javascript" src= "scripts/jquery-1.3.2-vsdoc2.js" &gt;&lt;/script&gt; &lt;script type= "text/"
                  JavaScript "&gt; $ (Function () {$ (" Li "). Toggle (function () {
              $ (this). css ({"List-style-type": "Disc", "Color": "Blue"}); The function () {$ (this). css ({"List-style-type": "Square", "Color": "Red"})
              The function () {$ (this). css ({"List-style-type": "None", "Color": "});
            ); }) &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;ul&gt; &lt;li style= "Cursor:pointer" &gt;click me&lt;/li&     Gt &lt;/Ul&gt; &lt;/body&gt; &lt;/html&gt; 

The result is a single click "Click Me" to transform the list symbol and the text color once.
Eight. Using the JQuery Event object
Event objects are naturally unavoidable with events. Because of the differences in the acquisition of event objects between different browsers and the properties of event objects, it is difficult to use event objects across browsers.
The event object is unified in jquery, and when the event handler is bound, the jquery-formatted event object is passed in as a unique parameter:
$ ("#testDiv"). Bind ("click", Function (event) {  });

For a detailed description of the Event object, you can refer to the jquery official documentation: Http://docs.jquery.com/Events/jQuery.Event
The jquery event object merges the differences in different browsers, such as the Event.target property in all browsers to get the trigger of the event (using the native event object in IE, access to event.srcelement).
The following are the properties that the jquery event object can support in expanding browsers:
Property name Describe Example
Event type. If you use an event handler to handle multiple events, you can use this property to get the event type, such as Click.
$ ("a"). Click (Function (event) {
  alert (event.type);
Get Event Trigger DOM object
$ ("a[href=http://google.com]"). Click (Function (event) {
  alert (event.target.href);
An additional parameter is passed in when the event is called.
$ ("a"). each (the function (i) {
  $ (this). bind (' click ', {index:i}, function (e) {
     alert (' Me index is ' + e.data.index) ;
For mouse events, mark the DOM element that was left or entered when the event was triggered
$ ("a"). Mouseout (function (event) {
  alert (event.relatedtarget);
The DOM object of the current triggering event before bubbling, equivalent to this.
$ ("P"). Click (Function (event) {
  alert (event.currentTarget.nodeName);

Result: P
In mouse events, the horizontal/vertical coordinates of the event relative to the origin of the page.
$ ("a"). Click (Function (event) {
  alert ("Current mouse position: + Event.pagex +," + Event.pagey);
The value returned by the previous event handler function
$ ("P"). Click (Function (event) {return
$ ("P"). Click (Function (event) {
  alert (event.result);

Result: "Hey"
The time stamp at which the event occurred.
var last;
$ ("P"). Click (Function (event) {
   if (last)
      alert (' time since last event ' + event.timestamp-last);
   last = Event.timestamp;
This is the property of the event object provided in the official jquery documentation. In the "jquery Combat" book also provides the following browser-supported properties, time relationship I didn't try every attribute, you can help verify that you are available in all browsers:
Property name Describe Example
Altkey Whether the ALT key is pressed. Press RETURN True
Ctrlkey CTRL key is pressed, press return True
Metakey Returns true if the META key is pressed.
The META key is the CTRL key for the PC machine, or the command key on the Mac machine.
Shiftkey If the SHIFT key is pressed, press return True
KeyCode Returns the pressed key for the KeyUp and KeyDown events. Case-insensitive, both a and a return 65.

Use the which property for the KeyPress event, because the which property is still reliable across browsing.
which For keyboard events, returns the numeric encoding of the key that triggered the event. For mouse events, return the mouse button number (1 left, 2, 3 right).
screenx/y For mouse events, gets the horizontal/vertical coordinates of the event relative to the screen origin
Event objects also have events in addition to owning attributes. There are some things that are certain to be used, such as canceling bubbling Stoppropagation (), and so on. The following is a list of functions for the jquery event object:
Name Description Example
Preventdefault ()
Cancels events that may cause any semantic action. For example, the <a> element's href link loading, the form submission, and click to cause the check box to toggle state.
$ ("a"). Click (Function (event) {
  event.preventdefault ();
  Do something
Isdefaultprevented ()
Have you invoked
Preventdefault ()
$ ("a"). Click (Function (event) {
  alert (event.isdefaultprevented ());
  Event.preventdefault ();
  Alert (event.isdefaultprevented ());
Stoppropagation ()
Cancel Event Bubbling
$ ("P"). Click (Function (event) {
  event.stoppropagation ();
  Do something
Ispropagationstopped ()
Have you invoked
Stoppropagation ()
$ ("P"). Click (Function (event) {
  alert (event.ispropagationstopped ());
  Event.stoppropagation ();
  Alert (event.ispropagationstopped ());
Stopimmediatepropagation ()
Cancels the execution of other event-handling functions and suppresses event bubbling.

If the same event binds multiple event-handler functions, calling this method in one of the event-handler functions will not continue to invoke the other event-handler function.
$ ("P"). Click (Function (event) {
  event.stopimmediatepropagation ();
$ ("P"). Click (Function (event) {
  //This function won ' t is executed
Isimmediatepropagationstopped ()
Have you invoked
Stopimmediatepropagation ()
$ ("P"). Click (Function (event) {
  alert (event.isimmediatepropagationstopped ());
  Event.stopimmediatepropagation ();
  Alert (event.isimmediatepropagationstopped ());

The Stoppropagation () in these functions are the most important functions that we use and are definitely used. The equivalent of manipulating the original event object's Event.cancelbubble=true to cancel bubbling.

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.