Explain the jQuery event in detail

  • 2021-07-12 04:30:48
  • OfStack

Event is an indispensable thing in Web application. When the user performs an operation in the application, such as triggering the execution of something when the mouse clicks, he can bind an event handler (event handler) to the event. Use jQuery's. on () method to bind arbitrary DOM events to selected elements and add event handlers. Assume the following HTML structure:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
</head>
<body>
 <button id="example" type="button">Click me!</button>
 <script src="http://code.jquery.com/jquery-1.11.2.js"></script>
 <script>
 // code here
 </script>
</body>
</html>

In < script > Element, where the event name is the first argument of the. on () method and the callback function of the event handler is the second argument:


$('#example').on('click', function(e) {
 alert('Clicked!');
});

So when the button element triggers the mouse click (click) event, it will execute the bound event handler and pop up a dialog box! The first parameter e of the callback function is an event object, through which we can get a lot of event-related information, such as event type, coordinate point of event occurrence, and some event methods. In addition to using an anonymous function like this, the callback function can also use a function reference identified by a variable:

$('#example').on('click', clickHandler);

Bind multiple events at the same time

In addition, jQuery also supports binding multiple events at the same time by separating multiple event names with spaces, such as mouseenter mouseleave, and binding mouse move-in and mouse move-out events to elements at the same time. The type property of the event object can be used to determine which event occurred:


$('#example').on('mouseenter mouseleave', function(e) {
 if (e.type === 'mouseenter') {
 // mouseenter
 } else {
 // mouseleave
 }
});

In addition to the above method, you can also pass in a key-value pair to bind multiple events:


$('#example').on({
 mouseleave: function() {
 // mouseleave
 },
 mouseenter: function() {
 // mouseenter
 }
});

Event context

When binding event handlers to multiple elements at the same time, you can use the context of event execution to simplify your code:


$('li').on('click', function() {
 var $this = $(this);
 $this.addClass('active');
});

The context keyword this refers to the native DOM element, so if you want to use the jQuery method, you need to wrap it as an jQuery object first.

Event delegate

Events go through a process of capture and bubbling. For compatibility, jQuery only uses bubbling of events, that is, after the target element triggers the event, it bubbles step by step until the top element node. Event bubbling allows you to bind the event handler of the target element to its ancestor element, and you can pass an optional selector string as the second parameter to the. on () method:

$(document).on('click', '#example', clickHandler);

This indicates that the mouse click event delegate for the element of id= "example" is bound to the document element, and when the target element (that is, the element of id= "example") triggers the mouse click event, it bubbles onto the document element, triggering the event handler. The advantage of using event delegates is that if there are many lists on the page, each bound to a mouse click event, there will be many event handlers, which will have an impact on performance. Using the principle of event bubbling, binding event handlers to the parent or ancestor elements of the target element can significantly reduce the number of event handlers and improve performance:

$('ul').on('click', 'li', clickHandler);

Another benefit of using event delegates is those that are dynamically added < li > Element also has an event handler. Personal comparison involves delegating all events to document elements for easy management, and without waiting until DOM is ready:


$(document)
 .on('click', 'selector-1', clickHandler)
 .on('focusin', 'selector-2', focusHandler);

Some events such as submit or change do not bubble in IE 8, but jQuery handles this, so you can use it with confidence. Events like focus and blur are recommended to be replaced by corresponding focusin and focusout events. For mouseover and mouseout events, it is recommended to use mouseenter and mouseleave instead in order to avoid the adverse effects caused by event bubbling.

Prevent event bubbling and default behavior

Calling the event object's. stopPropagation () method prevents event bubbling:


$('#example').on('click', function(e) {
 e.stopPropagation();
});

This way, when the click event occurs on the element, it will not bubble. jQuery has another method. Event bubbling is blocked after stopImmediatePropagation () is called and the event handler bound later on the element will not execute:


$('#example').on('click', function() {
 alert('Clicked-1!'); //  Will execute 
}).on('click', function(e) {
 e.stopImmediatePropagation();
}).on('click', function() {
 alert('Clicked-2!'); //  Will not be executed 
});

Calling the. preventDefault () method of the event object blocks the default behavior of the event:


$('#example').on('click', function(e) {
 e.preventDefault();
});

Returning false directly in the event handler can cancel bubbling and block default behavior at the same time:


$('#example').on('click', function() {
 return false;
});

This is equivalent to calling the. stopPropagation () and. preventDefault () methods on the event object at the same time. If there is no other operation, you can go one step further and abbreviate it as $('# example'). on ('click', false); .

For example, click the button to display the pop-up layer, and click other places in the document to hide it:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
0

Because the event bubbles, the pop-up layer will not be displayed, and you need to prevent the event bubbling in the event handler:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
1

Getting the Native Event Object

The event object referenced in the event handler is actually wrapped by jQuery, and sometimes it is necessary to use the browser native event object. To get the browser native event object, it can be obtained through the originalEvent attribute of the event object. For example, when you use drag events, you will use native event objects:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
2

Transfer data

You can pass in data to the event handler, which is stored in the data property of the event object:


$('#example').on('click', 1, function(e) {
 console.log(e.data); // 1
});

To distinguish event brokers, it seems that the data passed cannot be a direct string, but an object can be passed in instead:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
4

Custom Events

In addition to the browser's standard events, you can also bind event handlers for custom events, where the event name can be named arbitrarily:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
5

Event handlers for standard events can be triggered by browser native events, while event handlers for custom events can be triggered by jQuery's. trigger () method as follows, passing in the name of the event to be triggered as a parameter:

$('#example').trigger('sleep');

You can pass data to the event handler by passing in more parameters to the trigger () method, which is passed as an argument to the callback function:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
6

Apply examples to write asynchronous code using custom events:


$('#example').on('click', function(e) {
 alert('Clicked!');
});
7

When the foo function finishes execution, the done event of the element is triggered, and the previously bound doHandler function begins execution.

Event namespace

Namespaces can be added to either a browser standard event or a custom event, after the event name, separated by a. like click. widget, or multiple Namespaces click. widget. common can be added to a single event to more specifically fire or remove a particular event handler. For example, if an element is bound with two click events, click. tab and click. collapse, the event handler for click. collapse will be executed when the. trigger () method is used, but the event handler for click. tab will not be executed.

Remove binding events

You can remove a bound event handler using the. off () method in the following cases:

Removes all event handlers bound to the element without specifying any parameters. Specify an event name, such as. off ('click') to remove all click event handlers bound to the element. Specifying an event handler, such as. off ('click', clickHandler) means that only the event handler is removed (yes, anonymous functions cannot be removed in this way). Specifying an event namespace, such as. off ('. widget') means removing all event handlers in that namespace (for example, binding click. widget and change. widget event handlers will be removed), which can be used to remove various events bound to a component. An element that specifies an event broker, such as $(document). off ('click', '# example'), for which the event broker handler bound can be removed.

1 sexual incident

An event handler bound with the. one () method triggers only one execution, after which it is automatically removed:

$('#example').one('click', clickHandler);

Event throttling

There are several events in the browser that will be triggered frequently, such as scroll, resize, mousemove, etc., so the event handlers bound to these events will also be executed frequently, resulting in slow response of the page. To solve this problem, it is necessary to throttle events and reduce the execution frequency of event handlers:


var timer = 0; //  Use 1 Timer 
$(window).on('scroll', function() {
 if (!timer) {
 timer = setTimeout(function() {
 // Do something
 timer = 0;
 }, 200);
 }
});

Related articles: