[JQuery] events and animations

Source: Internet
Author: User

1. Events


1.1 load DOM

After the page is loaded, the browser adds an event to the DOM element through JavaScript. In JavaScript code, the window. onload method is usually used, while in jQuery, the $ (document). ready () method is used. The $ (document). ready () method and the window. onload method have similar functions, but they differ in execution timing. Window. the onload method is executed only after all the elements in the webpage are fully loaded into the browser, while $ (document ). the event handler registered by the ready () method can be called when the DOM is ready.

Because the event registered in the $ (document). ready () method is executed as long as the DOM is ready, the associated file of the element may not be downloaded at this time. To solve this problem, you can use another method load () in jQuery for page loading. The load () method binds a handler to the onload event of the element. If the processing function is bound to a window object, it is triggered after all the content is loaded. For example:

$(window).load(function(){});

Every time you call the $ (document). ready () method, new behaviors are pursued on the existing behaviors. These behavior functions are executed in the order of registration. It can also be abbreviated:

$(function(){});

In addition, $ (document) can also be abbreviated as $ (), for example:

$().ready(function(){});


1.2 event binding

After the document is loaded, if you want to bind events to the elements to complete some operations, you can use the bind () method to bind specific events to the matching elements. For example:

bind(type[,data],fn);

The first parameter is the event type, including: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup and error.

The second parameter is an optional parameter, which is an additional data object passed to the event object as the event. data Attribute Value.

The third parameter is the handler used for binding.

For example:

$("#mydiv").bind("click",function(){  $(this).next("div.content").show();});

Like the ready () method, the bind () method can also be called multiple times. Events such as click, mouseover, and mouseout are often used in programs. jQuery also provides a set of shorthand methods, such:

$("#mydiv").mouseover(function(){  $(this).next("div.content").show();});


1.3 merging events

JQuery has two merging events: the hover () method and the toggle () method. The syntax structure of the hover () method is as follows:

hover(enter,leave);

The hover () method is used to simulate a cursor hover event. When the cursor moves to an element, the specified first function is triggered. When the cursor moves out of this element, the specified second function is triggered.

toggle(fn1,fn2,...fnN);

The toggle () method is used to simulate consecutive mouse-clicking events. When you click an element for the first time, the specified first function is triggered. When you click the same element again, the specified 2nd functions are triggered, and so on, until the last one.


1.4 event bubbling

There can be multiple events on the page, or multiple elements can respond to the same event. Since IE-DOM and standard DOM implement event objects in different ways, it is difficult to get event objects in different browsers. JQuery has been extended and encapsulated to make it easy to obtain event objects in any browser. For example:

$("element").bind("click",function(event){});

Stopping event bubbling can prevent the event handler function of other objects from being executed. In jQuery, The stopPropagation () method is provided to stop event bubbling. For example:

$("span").bind("click",function(event){  var txt = $("#msg").html() + "<p>click!</p>";  $("#msg").html(txt);  event.stopPropagation();});

Elements in a webpage have their own default behaviors, for example, they will jump after clicking a hyperlink. In jQuery, The preventDefault () method is provided to prevent the default behavior of elements. For example:

$("#button").bind("click",function(event){  var txt = $("#msg").html() + "<p>click!</p>";  $("#msg").html(txt);  event.preventDefault();});

If you want to stop bubbling and default behavior on the event object at the same time, you can return false in the event processing function.


1.5 attributes of event objects

JQuery encapsulates common attributes of event objects in compliance with W3C specifications, so that event processing can run properly in various Browsers without browser type judgment. The common methods are as follows:

1) event. type (): gets the event type.

2) event. preventDefault (): block default event behavior.

3) event. stopPropagation (): prevents event bubbles.

4) event.tar get (): gets the element that triggers the event.

5) event. relatedTarget (): gets the relevant elements of an event.

6) event. pageX ()/event. pageY (): obtains the x and y coordinates of the cursor relative to the page.

7) event. which (): Click the event to get the left, center, and right-click the event.

8) event. metaKey (): Obtain the <ctrl> key in the keyboard event.

9) event. originalEvent (): point to the original event object.


1.6 remove event

The unbind () method can be used to delete element events. The syntax structure is as follows:

unbind([type][,data]);

If no parameter exists, all bound events are deleted. If the event type is provided, only binding events of this type are deleted. If the handler passed during binding is used as the second parameter and, only this specific event handler function will be deleted. For example:

$("#delAll").click()(  $("#btn").unbind("click"););

The structure of the one () method is similar to that of the bind () method, and the usage is similar to that of the bind () method. The syntax structure is as follows:

one(type[,data],fn);

After you use the one () method to trigger an event for the element, the event is executed only when it is triggered for the first time.


1.7 simulated operations

You can use the trigger () method to simulate user operations to achieve the click effect. For example:

$("#btn").trigger("click");

You can also use the simplified statement click () to achieve the same effect.

The trigger (type [, data]) method has two parameters. The second parameter is the additional data to be passed to the event processing function, which is passed as an array.

After the trigger () method triggers an event, the default browser operation is performed, for example:

$("input").trigger("focus");

The above code triggers not only the focus event, but also the focus of the input element itself. If you do not want to perform the default browser operation, you can use another method similar to triggerHandler.


2. Animation


2.1 show () and hide () Methods

The show () method and the hide () method are the most basic animation methods in jQuery. Call the hide () method for an element and change the display style of the element to "none". For example:

$("#mydiv").hide();

After hiding an element, you can use the show () method to set the display style of the element to the previous display status. For example:

$("#mydiv").show();

The show () method can specify a speed parameter, for example, specifying a speed keyword "slow", for example:

$("#mydiv").show("slow");

After running the code, the elements will be displayed slowly within 600 milliseconds. Other speed keywords include "normal" and "fast". In addition, you can also specify a number for the display speed, the Unit is milliseconds.


2.2 fadeIn () method and fadeOut () method

Unlike the show () method, the fadeIn () and fadeOut () methods only change the opacity of elements. The fadeOut () method reduces the opacity of an element within a specified period of time until the element completely disappears. The fadeIn () method is the opposite, for example:

$("#mydiv").fadeOut();


2.3 slideUp () method and slideDown () method

The slideUp () method and the slideDown () method only change the height of the element. If the value of the display attribute of an element is "none", when the slideDown () method is called, the element is displayed from top to bottom. The slideUp () method is the opposite. elements are hidden from bottom to top, for example:

$("#mydiv").slideDown();


2.4 Custom Animation method animate ()

If you need to take some advanced custom animations to solve more control problems, you can use the animate () method to customize the animation. The syntax structure is:

animate(params,speed,callback);

Params contains the ing of style attributes and values, such as {property1: "value1", property2: "value2 ",...}, speed is an optional speed parameter, and callback is a function executed when the animation is completed, for example:

$("#mydiv").animate({left:"+=500px"},300);

The "+ =" symbol or "-=" symbol indicates that the current position is accumulated or accumulated. To execute multiple animations at the same time, write the following code:

$("#mydiv").animate({left:"500px",height:"200px"},3000);

If you only want to execute the animation in sequence, you only need to split the Code. For example:

$("#mydiv").animate({left:"500px"},3000);$("#mydiv").animate({height:"200px"},3000);

Or:

$("#mydiv").animate({left:"500px"},3000).animate({height:"200px"},3000);


2.5 stop the animation and determine whether it is in the animation state

In many cases, you need to stop the animation of matching elements. You need to use the stop () method. The syntax structure is as follows:

stop([clearQueue][,gotoEnd]);

The clearQueue and gotoEnd parameters are optional. They are Boolean values. clearQueue indicates whether to clear the animation queue that has not been executed. gotoEnd indicates whether to directly jump the animation being executed to the final state.

When using the animate () method, you must avoid the inconsistency between the animation and the user's behavior caused by the accumulation of animation. The solution is to determine whether the element is in the animation State. For example:

if(!$("#mydiv").is("animated")){}


2.6 other animation Methods

There are also three animation methods specifically used for interaction in jQuery: toggle (speed, [callback]), slideToggle (speed, [callback]), fadeTo (speed, opacity, [callback]).

The toggle () method can switch the visible state of an element, for example:

$("#mydiv").click(function(){  $(this).next("div.content").toggle();});

The slideToggle () method switches the visibility of matching elements through height changes, for example:

$("#mydiv").click(function(){  $(this).next("div.content").slideToggle();});

The fadeTo () method can incrementally adjust the opacity of an element to a specified value. For example:

$("#mydiv").click(function(){  $(this).next("div.content").fadeTo(600,0.2);});



This article is from the "Fangyuan" blog and will not be reposted!

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.