jQuery Notes
- DOM represents an HTML document as a tree structure of nodes, wherein each node is an object representing a part of the document. The nodes are objects that have properties and methods, and these entities can be accessed via JavaScript and its libraries such as jQuery.
- It has become common practice to link the main JS file at the bottom of the HTML document, usually before the
</body>tag.
When the document is ready
There are two ways to handle the ‘document ready’ event
1 | $(document).ready(function(){ |
jQuery Selectors
${"*"} - select all elements
$("#id") - select an element with its id
${".class"} - select all elements with their class
${"div"} - select all elements with a tag
${"h2, div, p"} - select multiple tags
${"li:first"} - select the first li element, similarly, there are last, even, and odd
${":empty"} - select all elements that are empty
${":focus"} - select the element that has focus currently
${":root"} - select the html tag
jQuery Methods
1 | // addClass |
Binding events
on() adds an event handler for one or more events to matched elements
1 | $("#btn").on('click', function(){ |
Mousemove events
.mousemove() triggered when a mouse pointer moves over the area of the element(s).
For example, to receive the coordinates of the mouse pointer
1 | $(".mypanel").mousemove(function(e){ |
Event Source
We can refer to the event source with the $(this) syntax
1 | // there are multiple buttons in the HTML document, with class .btn |
Removing elements
1 | $("btn").click(function(){ |
is() method
Combined with $(this) method and if statement
1 | if ($(this).is('#panel1')) |
Effects
slideUp(),slideDown()- The first parameter is duration, which can be a string(slideUp('fast')orslideUp('slow')) or a number, the default value is 400msanimate(properties, duration)- The properties is an object of CSS properties and values
1 | $("rightBtn").click(function(){ |
fadeIn(),fadeOut()-fadeIn()fade the element(s) to opache, andfadeOut()fade the element(s) to transparent, the parameter is duration.
Asynchronous
get()requests data from a server with an HTTP GET request,the first parameter is a URL string to which to request is sent, the second parameter is a callback function which is executed if the request succeeds.when()excutes callback functions having asynchronous events1
$.when(task).done()