Checking When a Page is Ready For Your Code
The ready() method executes its function argument when the page is ready to work
$(document).ready(function(){
// function body
});
- Behind the scenes, the
ready()method add a listener for DOMContentLoaded events or for load events (in browsers that do not support HTML5 events a load event is fired instead)
There is a shorthand code for the ready() method:
$(function(){
// function body
});
If you do not wish to use jQuery but still run your code when the page is ready to work, place your script before the body closing tag.
Handling Events With on Method
The on() method handles all JavaScript events.
The on() method has two mandatory parameters:
- the names of the events the handler should respond to
- a function to be run when the event fires
$('selector').on('event-list', function(event) {
var $this = $(this);
$this.jQueryMethod();
});
- In the scope of the handler function the
thiskeyword refers to the node theonmethod is bound to.
Example: handling click event on anchor elements
See the Pen jQuery: on method for events by Massimiliano (@maxdesimone) on CodePen.
jQuery Event Types
| event interface | event types |
|---|---|
| FocusEvent | fucus, blur, change |
| KeyboardEvent | input, keydown, keyup, keypress |
| MouseEvent | click, doubleclick |
| FormEvent | submit, select, change |
| UIEvent | ready*, load, unload, error, resize, scroll |
* the ready event was introduced by jQuery
The Event Object
The jQuery event object has properties and methods.
- Event properties: type, which, data, target, pageX, pageY, timeStamp
- Event methods: preventDefault(), stopPropagation()
Note: event.target refers to the element that initiated the event while this keyword refers to the element to which the on is bound to.
Example: an handler function that tries to use all the properties of the event object
See the Pen jQuery: event object by Massimiliano (@maxdesimone) on CodePen.
The Two Optional Parameters for on Method
$('selector').on('event-list' [,'selector2'] [,object], function(event){ ... });
- The
on()method has two mandatory parameters and two optional parameters event-listis one or more event types the listener should responds toselector2is a second optional CSS selector for filtering descendant elements of the first matched setobjectis an optional object for passing extra information to the handler function. This object can be accessed in the handler throughevent.datareference- the handler
functionto be executed when the event fires. - The
eventobject is automatically passed to the handler
Event Delegation Example
The example below does event delegation:
- The on method is invoked on the <ul> element
- The on method second selector filters the
li>achildren of the <ul> element - In the on method scope the
thiskeyword refers to theli>achildren which raised the event
See the Pen jQuery event delegation by Massimiliano (@maxdesimone) on CodePen.
No comments:
Post a Comment