JQuery event usage example summary
- 2020-03-30 03:48:44
- OfStack
This article summarizes the usage of events in jQuery in the form of examples in detail, which has a good reference value for learning jQuery. Share with you for your reference. The specific usage is as follows:
1. Bind events to elements by method name:
$('li').click(function(event){})
2. Bind events to elements by the bind method:
$('li')
.bind('click',function(event){})
.bind('click',function(event){})
As you can see, with bind, you can bind multiple events to an element.
3. The namespace of the event
Why do you need an event namespace?
- suppose you bind 2 click events to the li element first.
$('li')
.bind('click',function(event){})
.bind('click',function(event){})
- now we want to log out one of the click events, which might look like this:
$('li').unbind('click')
But then we log out all the click events, which is not what we want. This problem is solved by using event namespaces, which are needed because they allow us to easily log out events.
How do I use the event namespace?
- when binding events for elements, add a namespace after the event name, in accordance with the format: event name. Namespace name.
$('li')
.bind('click.editMode',function(event){})
.bind('click.displayMode',function(event){})
- when cancelling the event, you can write:
$('li').unbind('click.editMode')
4. Types of events
The blur
change
click
The dblclick
The error
Focus.
focusin
focusout
keydown
keypress
keyup
The load
mousedown
mouseenter
mouseleave
mousemove
mouseout
moseover
mouseup
ready
The resize
scroll
The select
submit
unload
5. One method
Used to create a one-time event that is automatically deleted once it has been executed once.
$("p").one("click",function(){
$(this).animate({fontSize: "+=6px"});
})
6. Delete events
//Start by adding events to the element
$("p").click(function(){
$(this).slideToggle();
})
//Delete the element's events
$("button").click(function(){
$("p").unbind();
})
7. The Event attributes
In fact, it's a global property of jquery, jquery.event. Each time an Event is fired, the Event object instance is passed to the Event Handler.
Events can be created and triggered by the constructor of an Event.
var e = jQueery.Event("click")
jQuery("body").trigger(e);
You can even pass an anonymous object in an Event through the constructor.
var e = jQuery.Event("keydown", {keyCode : 64});
jQuery("body").trigger(e);
When used, the value of the anonymous object is obtained through event.data.keycode.
Not only can anonymous objects be passed in an Event through the jQuery.Event constructor, but you can also pass anonymous objects through events.
$("p").click({param1 : "Hello", param2 : "World"}, someFunction);
function someFunction(event){
alert(event.data.param1);
alert(event.data.param2);
}
As you can see, the key of the anonymous object can be obtained through event.data.
Through the Event object instance, you can also get other information, such as:
$("p").click(function(event){
alert(event.target.nodeName);
})
Above, get the element name of the trigger event through event.target.nodename.
Other attributes of jQuery.Event include:
The altKey is true if Alt is pressed, and on the Mac keyboard the Alt key is marked as Option
The ctrKey CTRL key is pressed
The shiftKey Shift key is pressed
Current element of the currentTarget bubbling phase
The data
MetaKey's Meta key is usually Ctrl, while on the Mac it's Command
The horizontal coordinates of the cursor relative to the page origin during a pageX mouse event
The vertical coordinates of the cursor relative to the page origin during the pageY mouse event
RelatedTarget triggers the mouse event when the cursor leaves or enters the element
The horizontal coordinate of the cursor with respect to the origin of the screen for a screenX mouse event
The vertical coordinate of the cursor with respect to the origin of the screen during the screenY mouse event
Result returns the most recent non-undefined value from the previous event handler
Target triggers the element of the event
Timestamp jquery.event the timestamp in milliseconds when an instance is created
Type event type, such as click
Which, if a keyboard event, represents the number of keys pressed, and if a mouse event, records the left, middle, or right key pressed
8. The Event method
Event.preventdefault () prevents default behavior
Event.stoppropgation () stops the "bubble", that is, stops further propagation up the DOM
Event. StopImmediatePropagation () to stop the further spread of all events
Event. IsDefaultPrevented ()
Event. IsPropgationStopped ()
IsImmediatePropgagationStopped ()
9. Live and on methods
This method allows us to create events for elements that do not yet exist. Unlike the bind method, events can be bound to all matched elements and are set to those that do not yet exist and need to be created dynamically. Also, the live method does not have to be in a $(function(){}) ready handler. After jQuery 1.7, it changed to the on method.
$("p").on("click", function(){
alert("hello");
})
If you want to cancel the registration event:
$("button").click(function(){
$("p").off("click");
})
10. The trigger method
The trigger method can be used when we want to manually trigger an event bound to an element.
$("#foo").on("click",function(){
alert($(this).text());
})
$("#foo").trigger("click");
You can also pass in parameters when binding events and arguments when triggering events.
$("#foo").on("custom", function(event, param1, param2){
alert(param1 + "n" + param2)
})
$("#foo").trigger("custom",["Custom","Event"]);
Instance created by jQuery.Event:
var event = jQuery.Event("logged");
event.user = "foo";
event.pass = "bar";
$("body").trigger(event);
You can even pass in an anonymous object when the trigger triggers the method:
$("body").trigger({
type: "logged",
user: "foo",
pass: "bar"
});
If you want to stop propagation of the triggered Event, you can use the stopPropgation() method of the jQuery.Event instance, or return false in any Event.
11. The triggerHandler method
The triggerHandler method differs from the trigger method in that the triggerHandler method does not execute default events for elements and does not "bubble".
//Bind a focus event to an element
$("input").focus(function(){
$("<span>Focused</span>").appendTo("#id").fadeOut(1000);
})
//Use the triggerHandler trigger
$("#id").click(function(){
$("input").triggerHandler("focus");//The default behavior of focus is not triggered, which is to enter the text box
})
//With the trigger to trigger
$("#id").click(function(){
$("input").trigger("focus");//Both the default behavior and binding behavior of foucs are triggered
})
12. Event bubbling and event delegation
What is event bubbling?
I have this piece of code.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div>
<p><a href="#foo"><span>I am a Link!</span></a></p>
<p><a href="#bar"><b><i>I am another Link!</i></b></a></p>
</div>
</body>
</html>
Now bind the click events to all the elements of the page, including window and document.
$(function () {
$('*').add([document, window]).on('click', function(event) {
event.preventDefault();
console.log(this);
});
});
When any element of the page is clicked, the click event starts with the current element, propagates up to the top-level element, in this case, window.
How do I stop the event from bubbling?
Above, only the click event is bound to a, not to it.
How to effectively utilize event bubbling?
In jquery, event delegates make good use of event bubbling.
<html>
<body>
<div id="container">
<ul id="list">
<li><a href="http://domain1.com">Item #1</a></li>
<li><a href="/local/path/1">Item #2</a></li>
<li><a href="/local/path/2">Item #3</a></li>
<li><a href="http://domain4.com">Item #4</a></li>
</ul>
</div>
</body>
</html>
Now, we want to bind events to the a tag in the existing li by saying:
$( "#list a" ).on( "click", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
But what if you add new li and a to your existing ul?
$( "#list" ).append( "<li><a href='http://newdomain.com'>Item #5</a></li>" );
As a result, nothing happens when you click on a in the newly added li. So how do you bind events to dynamically added elements?
If we can bind the event to the parent element of a, then the child dynamic element generated in the parent element will also have the behavior of binding the event.
$( "#list" ).on( "click", "a", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
Above, we bind the click event to the ul with the parent element id list of a, and the second parameter in the on method, in this case a, is the actual executor of the event. The specific process is as follows:
- click on a TAB
- according to the event bubbling, the click event of the parent element ul of a was triggered
- the real executor of the event is a
Event delegates allow us to bind events to parent elements, which is equivalent to binding events to all child elements, whether static or dynamically added.
13. Toggle method
Allows us to execute multiple events in sequence, and then execute the first event after the last event has been executed.
$('img[src*=small]').toggle({
function(){},
function(){},
function(){}
});
14. Mouseenter and mouseleave methods
$(element).mouseenter(function(){}).mouseleave(function(){})
15. Hover method
$("p").hover(function(){
$("p").css("background-color","yellow");
},function(){
$("p").css("background-color","pink");
});
I believe that this article has a certain reference value for your jQuery programming.