Detailed explanation of jQuery events in JavaScript
Because JavaScript runs in a single thread mode in the browser, after the page is loaded, once all the JavaScript code on the page is executed, you can only rely on the trigger event to execute the JavaScript code.
After receiving the user's mouse or keyboard input, the browser will automatically trigger the corresponding event on the corresponding DOM node. If the node has bound the corresponding JavaScript processing function, the function will be called automatically.
Because different browsers have different codes for binding events, writing code with jQuery shields the differences between different browsers. We always write the same code.
For example, suppose to pop up a prompt box when a user clicks a hyperlink, we bind a click event with jQuery:
/* HTML: * * <a id="test-link" href="#0">Let me try</a> * */ // Get the jQuery object of the hyperlink: var a = $('#test-link'); a.on('click', function () { alert('Hello!'); });
Measured: Let me try
The on method is used to bind an event. We need to pass in the event name and the corresponding handler function.
Another more simplified method is to call the click() method directly:
a.click(function () { alert('Hello!'); });
The two are completely equivalent. We usually use the latter way.
The events that jQuery can bind mainly include:
Mouse event
- click: triggered when the mouse clicks;
- dblclick: triggered when the mouse double clicks;
- mouseenter: triggered when the mouse enters;
- mouseleave: triggered when the mouse is moved out;
- mousemove: triggered when the mouse moves inside the DOM;
- hover: two functions are triggered when the mouse enters and exits, which is equivalent to mouseenter plus mouseleave.
Keyboard events
Keyboard events only act on the DOM of the current focus, usually < input > and < textarea >.
- keydown: triggered when the keyboard is pressed;
- keyup: triggered when the keyboard is released;
- keypress: triggered after pressing the key once.
Other events
- Focus: triggered when DOM obtains focus;
- blur: triggered when DOM loses focus;
- Change: triggered when the contents of < input >, < Select > or < textarea > change;
- submit: triggered when < form > is submitted;
- ready: triggered when the page is loaded and the DOM tree is initialized.
Among them, ready only works on the document object. Since the ready event is triggered only once after the DOM completes initialization, it is very suitable for writing other initialization codes. Suppose we want to bind the submit event to a < form > form. The following code has no expected effect:
<html> <head> <script> // Wrong code: $('#testForm').on('submit', function () { alert('submit!'); }); </script> </head> <body> <form id="testForm"> ... </form> </body>
When JavaScript executes here, < form > has not been loaded into the browser, so $('#testForm) returns [], and no event is bound to any DOM.
Therefore, our own initialization code must be placed in the ready event of the document object to ensure that the DOM has completed initialization:
<html> <head> <script> $(document).on('ready', function () { $('#testForm).on('submit', function () { alert('submit!'); }); }); </script> </head> <body> <form id="testForm"> ... </form> </body>
So there's no problem writing. Because the relevant code will be executed after the DOM tree is initialized.
Since the ready event is widely used, it can be simplified as follows:
$(document).ready(function () { // on('submit', function) can also simplify: $('#testForm).submit(function () { alert('submit!'); }); });
It can even be simplified to:
$(function () { // init... });
The above writing is the most common. If you encounter $(function() {...}) Remember that this is the ready event handler of the document object.
Event handling functions can be bound repeatedly, and they will execute in turn:
$(function () { console.log('init A...'); }); $(function () { console.log('init B...'); }); $(function () { console.log('init C...'); });
Event parameters
For some events, such as mousemove and keypress, we need to obtain the values of mouse position and keys, otherwise it is meaningless to listen to these events. All events will be passed into the Event object as parameters. You can get more information from the Event object:
$(function () { $('#testMouseMoveDiv').mousemove(function (e) { $('#testMouseMoveSpan').text('pageX = ' + e.pageX + ', pageY = ' + e.pageY); }); });
Unbind
A bound event can be unbound through off('click', function):
function hello() { alert('hello!'); } a.click(hello); // Binding event // Unbind after 10 seconds: setTimeout(function () { a.off('click', hello); }, 10000);
It should be noted that the following expression is invalid:
// Binding event: a.click(function () { alert('hello!'); }); // Unbind: a.off('click', function () { alert('hello!'); });
This is because as like as two peas anonymous functions, the two anonymous functions are two different function objects, off('click', function () {...}). Cannot remove the first anonymous function that is bound.
To achieve the removal effect, you can use off('click ') to remove all the handlers of the bound click event at once.
Similarly, a parameterless call to off() removes all types of event handlers that have been bound at once.
Event trigger condition
One thing to note is that events are always triggered by user actions. For example, we monitor text box content changes:
var input = $('#test-input'); input.change(function () { console.log('changed...'); });
When the user enters in the text box, the change event is triggered. However, if you use JavaScript code to change the value of the text box, the change event will not be triggered:
var input = $('#test-input'); input.val('change it!'); // Unable to trigger the change event
Sometimes, we want to trigger the change event with code. We can directly call the change() method without parameters to trigger the event:
var input = $('#test-input'); input.val('change it!'); input.change(); // Trigger change event
input.change() is equivalent to input Trigger ('change '), which is short for trigger() method.
Why do we want to trigger an event manually? If we don't as like as two peas, we will have to write two identical codes.
Browser security restrictions
In the browser, some JavaScript code can be executed only when triggered by the user, for example, window Open() function:
// Unable to pop up a new window, it will be blocked by the browser: $(function () { window.open('/'); });
These "sensitive codes" can only be triggered by user actions:
var button1 = $('#testPopupButton1'); var button2 = $('#testPopupButton2'); function popupTestWindow() { window.open('/'); } button1.click(function () { popupTestWindow(); }); button2.click(function () { // Do not execute popputtestwindow() immediately, and execute after 3 seconds: setTimeout(popupTestWindow, 3000); });
When the user clicks button1, the click event is triggered. Since popputtestwindow() is executed in the click event handler function, which is allowed by the browser, the click event of button2 does not immediately execute popputtestwindow(), and the delayed popputtestwindow() will be intercepted by the browser.