Learning jQuery

Reading time ~5 minutes

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


  • :not()
  • :even
  • :odd
  • :first
  • :last

Attribute selector


use a[href$=] to select end with …

Custom selector

child selector: :nth-child()


  • 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.


  • 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( 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
    focus: function() { $(this).addClass("focused"); },
    keyup: function(e) {
      $("#which b").text(e.which);
    blur: function() { $(this).removeClass("focused"); }


With .target, we can determine which element in the DOM was the first to receive the event.


For key or mouse events, this property indicates the specific key or button that was pressed.


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) {
    } else {

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) {

    var keyup_event = $.Event({
      type: "keyup"

    keyup_event.which = 75;


Event delegation

      <a href="#">Remove</a>
    <!-- 29 more list items, each with a remove anchor -->
  // This callback is bound to each anchor, making 30 event handlers in memory

  $('a').on('click', function(e) {

  // 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) {

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.


  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)

Styling and Animation


  • 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);


  • accept duration
  • ‘fast’: 200ms
  • default: 400ms
  • ‘slow’: 600ms


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



  • custom animation


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.

  1. Some DOM properties, such as nodeName, nodeType, selectedIndex, and childNodes, have no equivalent attribute, and therefore are not accessible via .attr().
  2. 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() 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


  • not only selection, but also create new DOM element


  • insertBefore();
  • prependTo();
  • insertTO();

insertAfter() vs after();

  <div class="container">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>
  $( ".inner" ).after( "<p>Test</p>" );
  $( "<p>Test</p>" ).insertAfter( ".inner" );
  <div class="container">
    <div class="inner">Hello</div>
    <div class="inner">Goodbye</div>

Sending Data with Ajax


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() // $.getJSON: showhand Ajax function

  • $.getJSON(url[,data][,success]) is equivalent to:
    dataType: "json",
    url: url,
    data: data,
    success: success
  • $.get(url[,data][,success][,dataType]) is equivalent to:
    dataType: dataType,
    url: url,
    data: data,
    success: success
  • getScript()

Pass data to server:

post request


    type: "POST",
    url: url,
    data: data,
    success: success,
    dataType: dataType



  $(document).ajaxStart(function() {
  }).ajaxStop(function() {

to_param in Ruby on Rails

If I want a custom slug=======================I walk through this cutstom slug.1. create migration `add_slug` to add a column inside the...… Continue reading

What is ORM in Rails mean?

Published on July 14, 2017