This is my short note while learning jQuery. I still left some highlight without contents. But it is as good as an gateway to search for the contents.
why use jQuery
- easily modify DOM(use css selector)
- easily modify CSS
- more animation
- jQuery can chain function together
- use AJAX to receive/send data without refresh the page
selected element
jQuery objects are different from DOM element
$( "#foo" )[ 0 ]; // Equivalent to document.getElementById( "foo" )
$( "#foo" ).get( 0 ); // Identical to above, only slower.
.eq()
will return a jQuery object
css selector
filter
:not()
:even
:odd
:first
:last
Attribute selector
$('a[href^="mailto:"]').addClass('mailto');
use a[href$=]
to select end with …
Custom selector
child selector: :nth-child()
:contains()
:
- select element contains specific text
Form selector
- :input
- :button
- :enabled
- :disabled
- :checked
- :selected
filter() vs find() in jQuery:
To simple:
- filter() – search through all the elements.
- find() – search through all the child elements only.
Traverse
- children()
- next()/nextAll()
- prev()/prevAll()
- parent()/parents()
- With parent, it never looks at the current element for consideration. With closest(), it first looks at the current element to see if it is a match
- siblings()
- end():
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
.each
: The jQuery each method will pass the DOM element as an argument to the callback function
function toggleCategories() {
$categories.each(function(i) {
var $checkbox = $(this),
Handling Event
On
.on( events [, selector ] [, data ], handler )
events in MDN, example: ‘click’, ‘keypress’, ‘submit’
on('change', handler)
:
handler can be checkbox, radiobox, input, select, textarea
- you can bind multiple events:
// Multiple events bound with options object
$("#text").on({
focus: function() { $(this).addClass("focused"); },
keyup: function(e) {
$("#which b").text(e.which);
$(this).val("");
},
blur: function() { $(this).removeClass("focused"); }
});
target
With
.target
, we can determine which element in the DOM was the first to receive the event.
event.which
For key or mouse events, this property indicates the specific key or button that was pressed.
trigger
Execute all handlers and behaviors attached to the matched elements for the given event type.
$(document).off('keypress').on('keypress', function(e) {
if (e.which !== characterCode) {
return;
} else {
$('a').trigger("click");
}
});
create event object
The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional.
Check trigger’s documentation to see how to combine it with your own event object.
// Create a new event object and use it to trigger an event with properties pre-set
$("#trigger_k").on("click", function(e) {
e.preventDefault();
var keyup_event = $.Event({
type: "keyup"
});
keyup_event.which = 75;
$("#text").trigger(keyup_event);
});
Event delegation
<ul>
<li>
<p>Bananas</p>
<a href="#">Remove</a>
</li>
<!-- 29 more list items, each with a remove anchor -->
</ul>
// This callback is bound to each anchor, making 30 event handlers in memory
$('a').on('click', function(e) {
e.preventDefault();
$(this).closest('li').remove();
});
// This callback is bound to a single element, yet it is able to process click events on any of the remove anchors within it.
$('ul').on('click', 'a', function(e) {
e.preventDefault();
$(e.target).closest('li').remove();
});
use $.proxy()
$.proxy()
, which is the functional equivalent of JavaScript’s built in bind method. It came before the bind method, which was introduced in ES5.
example:
var person = {
firstName: "Rachel",
lastName: "Smith",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
var getName = $.proxy(person.fullName, person); // same as person.fullName.bind(person)
console.log(getName());
Styling and Animation
.css
- Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.
position vs offset
The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. When positioning a new element near another one and within the same containing DOM element, .position() is the more useful.
// Position and offset
$("#pinboard p").on("click", function() {
var $p = $(this),
position = $p.position(),
offset = $p.offset();
$("#position").html("Left: " + position.left + "<br />Top: " + position.top);
$("#offset").html("Left: " + offset.left + "<br />Top: " + offset.top);
});
});
hide()/show()
- accept duration
- ‘fast’: 200ms
- default: 400ms
- ‘slow’: 600ms
toggle(display)
type: boolean eg. .toggle(checked)
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
fadeIn/fadeOut /fadeToggle
slideDown()/slideUp()/slideToggle
animate()
- custom animation
finish();
Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.
Manipulating DOM
addClass/ removeClass/ toggleClass
attribute and properties
distinction between HTML attributes and DOM properties. Attributes are the values given in quotation marks in the HTML source for the page, while properties are the values as accessed by JavaScript.
- Some DOM properties, such as nodeName, nodeType, selectedIndex, and childNodes, have no equivalent attribute, and therefore are not accessible via .attr().
- data types may differ: the checked attribute, for example, has a string value, while the checked property has a Boolean value.
.attr() and .removeAttr()
.prop / removeProp
.val()
val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null.
insert DOM
$(html)
- not only selection, but also create new DOM element
insert
- insertBefore();
- prependTo();
- insertTO();
insertAfter() vs after();
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$( ".inner" ).after( "<p>Test</p>" );
$( "<p>Test</p>" ).insertAfter( ".inner" );
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div>
Sending Data with Ajax
.load()
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function.
- not global
$.get()
$.get() // $.getJSON: showhand Ajax function
$.getJSON(url[,data][,success])
is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
$.get(url[,data][,success][,dataType])
is equivalent to:
$.ajax({
dataType: dataType,
url: url,
data: data,
success: success
});
getScript()
Pass data to server:
post request
$.post(url[,data][,success][,dataType])
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
ajaxStart()/ajaxStop()/ajaxError()/ajaxSuccess()
example:
$(document).ajaxStart(function() {
$loading.show();
}).ajaxStop(function() {
$loading.hide();
});