jQuery event handling (Events)

 

Most of jQuery's event handling functions provide two purposes, one is to call a function with parameters-to bind the event handling function ; the other is to call a function without parameters-to trigger the event .

With parameters, for example, when binding all paragraphs to trigger the click event, change the background color to blue:

$('p').click(function() {
  $(this).css('background-color', 'blue');
});

Without parameters, for example, to trigger the click event of all paragraphs:

$('p').click();
The event handler thisfor the "DOM element" is triggered, rather than jQuery object.

In the above code, we use the click function defined by jQuery to process the click event. However, jQuery also has functions related to other DOM events. For example, the following jQuery event functions are also used in the same way:

eventTriggering conditions
blurWhen the object loses focus
changeWhen the content of the object changes
clickWhen the mouse clicks on an object
dblclickWhen the mouse is double-clicked on an object
errorWhen an error occurs when downloading images or files
focusWhen the object is clicked or gets focus
keydownWhen keyboard keys are pressed
keypressAfter pressing and releasing the keyboard keys
keyupWhen pressing and releasing a keyboard key
loadWhen the web page or image is downloaded
mousedownWhen pressing the mouse button
mousemoveMouse movement between over and out
mouseoutWhen the mouse leaves around an object
mouseoverWhen the mouse leaves around an object
mouseupWhen you release the mouse button
resizeWhen the window or frame size is changed
scrollWhen the scroll is pulled
selectWhen text is selected
submitWhen the send button is pressed
beforeunloadBefore the user closes (or leaves) the page
unloadWhen the user closes (or leaves) the page

jQuery event object

For all jQuery event handlers, you can pass in a parameter as the event object, as in the following example:

$(document).click(function(event) {
  alert(event.pageX);
});

The above example is used to get the position of the mouse cursor relative to the page, the point is! This code can also be executed on IE (Note: The original IE browser event has no pageX attribute). Why? Because jQuery helped you solve the cross-browser problem in event handling in advance-"jQuery modified the event object to make it conform to the W3C standard", so you don't need to repeat it again if (window.event), you only need to understand and use the standard Event attributes!

jQuery's event binding processing function

.hover(handlerIn, handlerOut)

$(selector).hover(handlerIn, handlerOut)In fact, is $(selector).mouseenter(handlerIn).mouseleave(handlerOut);a simplified version.

When the mouse moves over a matching element, the first function (handlerIn) is triggered; when the mouse moves out of the element, the second function (handlerOut) is triggered.

For example, when the mouse moves into the li element, add *** after it, and delete it when it moves out:

$('li').hover(
  function() {
    $(this).append($('<span> ***</span>'));
  }, function() {
    $(this).find('span:last').remove();
  }
);

.bind(eventType, handler) unbind(eventType)

In addition to the direct use of a specific event function to bind the event (ie .click ()), you can also use .bind()to do.

For example, when the mouse clicks on the foo element, an alert message pops up:

$('#foo').bind('click', function() {
  alert('User clicked on foo.');
});

.unbind() Used to remove event handling functions, for example:

// Remove all event handlers bound on the foo element
$('#foo').unbind();
// Only remove all click event handlers bound to the foo element
$('#foo').unbind('click');

// Only remove specific processing functions for specific events
var handler = function() { alert('hi'); };
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);

bind and unbind also allows us to reach a custom event handler function:

$('#foo').bind('myEvent', doSomething);

As above, we customize an event called myEvent, but this is not a DOM standard event, how to trigger it? The answer is to use the "trigger" function that will be discussed next to trigger myEvent.

.trigger(eventType [, extraParameters])

Trigger the event, where extraParameters are the parameters (an array or object) to be passed to the event handler.

For example, to trigger the custom myEvent event above:

$('#foo').trigger('myEvent');

Of course, it can also be used to trigger general events:

$('#foo').trigger('click');

.one(events, handler)

If you only trigger the "one time" event, use the one function to do the bind action. When the event is triggered once, it will automatically unbind.

$('#foo').one('click', function() {
  alert('This will be displayed only once.');
});

.on() .off()

From the beginning of jQuery 1.7 .on()is recommended to use the main event handler binding function, but also to replace .bind().live()and .delegate().

.bind() The disadvantage is that bind directly binds the event handling function to the selected element, so at the time of binding, the element must already exist in the DOM!

For example, this is useless:

// // At this time there is no #foo element on the page
$('#foo').bind('click', function() { alert('hi'); });
$(document.body).append('<button id="foo">hi</button>');
// Click the button, there will be no alert!

.on() makes full use of the principle of browser event bubbling and the technique of event delegation!

Under IE8, events like change and submit will not be bubble, but jQuery will also help you deal with this problem at the bottom (yay cross-browser)!

Because of the event delegation technique, .on() can be used to bind events to handle existing or non-existing DOM elements, like you can bind to $(document).on() to listen to all DOM events.

There is another performance advantage of using event delegation. You don’t need to bind event processing to a bunch of elements separately (for example, bind thousands of elements, the performance is poor), you can only bind to the document or container element to get significant Performance improvement.

For example, bind a bunch of click event processing to a bunch of tr elements under #dataTable tbody:

$('#dataTable tbody tr').on('click', function() {
  // Here this points to #dataTable tbody tr this DOM element
  // Use $() to convert this to jQuery object
  console.log( $(this).text() );
});

VS binds a click event processing to #dataTable tbody, and then listens to the click event from tr bubble:

$('#dataTable tbody').on('click', 'tr', function() {
  // Here this refers to the DOM element that conforms to the selector, which is tr
  console.log( $(this).text() );
});

The third parameter of .on() can be used to pass data into the event processing function:

function greet(event) {
  alert('Hello ' + event.data.name);
}

$('button').on('click', {
  name: 'Karl'
}, greet);

$('button').on('click', {
  name: 'Addy'
}, greet);

Use .off() to remove event handling functions, for example:

// Remove all event handling for p elements
$('p').off();
// Remove the click event handling of all p elements
$('p').off('click');
// Remove #foo's click event delegation
$('p').off('click', '#foo');

You can also use blanks to separate multiple events and bind event processing at the same time:

$('#cart').on('mouseenter mouseleave', function(event) {
  $(this).toggleClass('active');
});

Name the event (Namespacing events)

Although we can use unbind / off to remove events, it will remove all bound event processing at once. What's the solution? The answer is to use Namespacing events provided by jQuery! Just look at an example to understand what it is:

// Bind the event processing function; and name the event name
// The event name must be followed by a period.
$('#foo').on('click.name', function() { alert(1); });
$('#foo').on('click.name', function() { alert(2); });
// Trigger all events whose name is name
$('#foo').trigger('.name');
// Remove all events whose name is name
$('#foo').off('.name');

Namespacing events simply means to give the event a name (namespace), understand it :)

`$(document).ready(function()

Last, but very important and very common. In jQuery, most of the operations are based on HTML DOM, so we must make sure that the page file has been completely downloaded before starting to execute your program. jQuery provides the following function to handle the DOM ready event (DOMContentLoaded):

$(document).ready(function() {
  //Put the code you want to execute here
});

You can also write:

$(function() {
  //Put the code you want to execute here
});
jQuery's DOM ready event is to start executing the program when the HTML DOM is ready, unlike the commonly used window.onload, the onload event will be triggered after all pictures and external files have been downloaded.

DOMContentLoaded & external style sheet?

As mentioned above, the triggering of the DOMContentLoaded event does not have to wait until the download of the image file, etc. is complete, but the question here is, does it need to wait until the "External CSS Styles" download is complete? Regarding this point, the triggering of the DOMContentLoaded event by various browsers is indeed inconsistent. In Opera, the browser does not wait for the external style sheet to be downloaded and then triggers DOM ready; while Firefox waits until the external CSS is loaded. Therefore, if you change the CSS properties of an element in the jQuery ready event, for Opera, the properties you modify are likely to be overwritten by the external style sheet that is loaded next, which will cause cross-browser processing problems. But if you cannot avoid changing the CSS properties at the initial stage of the page, we can use the load event to avoid this problem to make sure that the event will be triggered after the external style sheet is downloaded:

$(window).load(function() {
  // Run code
});

Post a Comment

0 Comments