What's done in jQuery

jQuery Events: $ (function), ready

Document loaded

Three events set the pace for scripting in the life cycle of a website:

$ (function () {
(DOMContentLoaded)
The browser has fully loaded the HTML, the DOM tree is in place, but external resources such as images and style sheets have not yet been loaded.
$ (window) .on ("load", handler)
(load)
The browser has the document and all external resources (especially all images) are loaded.
$ (window) .unload (function ()
(beforeunload / unload)
When the browser leaves the page.

Before script statements can be executed, the elements involved must be fully loaded.

It does not work
<!DOCTYPE html> <html> <head> <title>jQuery aufrufen</title> <script src="…jquery-3.2.1.min.js"></script> <script> let length = $("h2").length; console.log(length); </script> </head> <body> … </body> </html>

The sequence is important: First the h1 element has to be loaded, only then can jQuery access the element.

This is how it becomes a shoe
<script asnc src="…jquery-3.2.1.min.js"></script> <script> $(function() { let length = $("h2").length; console.log(length); }); </script>

Until the document with all elements such as images and CSS files is completely loaded, there may be a noticeable delay in starting the script. If only the HTML document is required for the script - but not elements such as images and films - jQuery could start faster than pure Javascript thanks to $ (function). Before the browser DOMContentLoaded support on a broad basis, the quick intervention was a great advantage of jQuery compared to pure Javascript.

jQuery 3: $ (function ()

Before jQuery 3, there were several versions of the ready call

$ (function () // directly - not on an individual element $ (document) .ready (handler) // on the document element $ ("iframe") .ready (handler) // on an individual element $ () .ready (handler) // on an empty element

Source: .ready ()

These variants are functionally the same. The handler function is called as soon as the DOM is fully loaded - regardless of the element on which the event is called.

The call with $ ("img") .ready or $ ("iframe") .ready compared to $ (document) .ready it sounds like the function is called when the image has been loaded - but it doesn't work that way. ready fires when the DOM is fully loaded.

With jQuery3, all versions except $ (function () as deprecated - out of date.

$ (function () vs DOMContentLoaded

The native Javascript (also as Vanilla Javascript an event is available today with which The cathedral is loaded and can be traversed can be called up just as well as with $ (function () - DOMContentLoaded.

document.addEventListener ("DOMContentLoaded", function () {let length = document.querySelectorAll ("h2"). length; console.log ('DOMContentLoaded' + length);});

However, the callback function is not executed if the event has already fired (e.g. by a previously loaded external script).

jQuery checks the readyState status of the document and executes the callback function immediately.

When is .ready () needed?

$ (function () is only needed if the script is loaded in the head element of the page.

If, however, the script is only loaded at the end of the body element, all elements of the page are loaded anyway.

That is why scripts are now preferred to be loaded at the end of the HTML document before the closing body tag. This ensures that the DOM is loaded and the elements can be accessed. Without $ (function () and without DOMContentLoaded:

Move scripts to the end of the document
<!DOCTYPE html> <html> <head> <title></title> </head> <body> … <script asnc src="/dist/jquery-3.2.1.min.js"></script> <script> let length = $("h2").length; console.log ( length ); </script> </body>

jQuery: Load image asynchronously

<img class="loading" src="pixel.gif">

pixel.gif is a 1px gif image. The CSS for the blank GIF is

.loading {background: url ("loading.gif") 50% no-repeat; width: 100%; border: 1px solid silver}

loading.gif is an animated GIF, a classic waiting icon.

The image is generated programmatically with jQuery (let $ downloadingImage = $ (""). As soon as the path to the picture is noted, the loading process begins and as soon as the loading process is finished, the event fires.

Load image asynchronously with Javascript

That is short and manageable. But embed jQuery just because an image is loaded asynchronously? Today, natural Javascript without additives is just as advanced.

(function () {let image = document.querySelector (". loading"); let loading = new Image (); loading.onload = function () {image.src = this.src;} loading.src = "buffalo. jpg ";}) ();

Bind events to an element

Category: Event Handler Attachment lists the jQuery functions for event handling. The most important are on () and off (). on () binds an event to the callback function, off () releases the callback function.

$ ('# test'). on ("mousemove", onMouseOver); $ ('# test'). on ("click", onMouseKlick); $ ('# test'). on ("mouseleave", onMouseLeave); function onMouseOver (possibly) {$ ('# test'). text (possibly.type + ":" + possibly.pageX + '' + possibly.pageY); } function onMouseKlick (possibly) {$ ('# test'). text (possibly.type + ":" + possibly.pageX + '' + possibly.pageY); $ ('# test'). off ('mousemove', onMouseOver); } function onMouseLeave (evt) {$ ('# test'). text ('Get the mouse out'); }

The example tracks the mouse coordinates and releases the mouseover handler when you click on the test field. If IE8 and older versions of Internet Explorer no longer have to be supported, the difference to the classic Javascript Event API is no longer great for simple examples like here.

But jQuery on () cannot trigger just one event. To listen for another event with the same function

$ ('# test'). on ("mousemove swipe", onMouseOver);

The events are simply separated from each other by a space.

jQuery - prevent events with preventDefault ()

A recurring task: when you click on a link, Javascript adds additional elements - in this example a larger version of the image without opening an additional browser window. If Javascript is not activated, the click follows the link in the conventional way. So that the original action - following the link - is not carried out when Javascript is active, the original action must be prevented.


… $ ('. popup'). click (function (event) {$ (this) .parent (). prepend (' '); event.preventDefault (); $ (' img # popped '). click (function () {$ (this) .remove ();});}) ;

In order to actually prevent the event (following the link), the function 'event' must be passed as a parameter. event.preventDefault () prevents the original action - following the link - from being carried out.

Reload images with jQuery

Sprite for the talking raven by frankes

So that a GIF animation is reloaded and restarted when hovering with the mouse:

$ (function () {$ (". talk"). mouseover (function () {$ (this) .attr ({src: "talking-rabe.gif"});})});

bind, delegate, die, error, live, load, toggle, unbind, undelegate, unload are no longer wanted in jQuery version 3.

blur, change, click, dblclick, dblclick, focus, focusin, focusout, hover, keydown, keypress, keyup, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, resize, scroll, select, submit
Triggering or assigning the event
event.currentTarget
The current DOM element within the bubbling phase
event.data
Data that is passed to the event method if the currently executed event handler is connected.
event.delegateTarget
Returns the element to which the current event handler is bound.
event.isDefaultPrevented
Returns whether event.preventDefault is instructed.
event.isImmediatePropagationStopped
Returns whether event.stopImmediatePropagation was called for the Event object.
event.isPropagationStopped
Returns whether event.stopPropagation was called for the event object.
event.namespace
Returns the namespace at the time it was triggered.
event.pageX
Returns the position of the mouse relative to the left edge of the document.
event.pageY
Returns the position of the mouse relative to the top of the document.
event.preventDefault
Prevents the specified action of the event.
event.relatedTarget
Returns the element entered or exited by moving the mouse.
event.result
Contains the last / previous value returned by the event handler.
event.stopImmediatePropagation
Prevents other event handlers from being called.
event.stopPropagation
Prevents the event from bubbling so that parent elements are not notified of the occurrence of the event.
event.target
Returns the element that triggered the event.
event.timeStamp
Returns the time of occurrence of the event as milliseconds from 1/1/1970.
event.type
Returns the type of the event.
event.which
Returns the key or mouse button.
off
Removes the event handler that was assigned with on
on
Assigns the event handler to the element
one
Assigns one or more event handlers to the selected elements. This handler can only be assigned to the element once per element.
$ .proxy
Takes an existing function and returns a new one with a special context
ready
Function is executed when the DOM is fully loaded.
trigger
Triggers all events that are linked to the selected element.
triggerHandler
Triggers all functions that are linked to the event for the selected element.

External sources