jQuery Guide

This guide has the information you need to know about jQuery to get started. 

Basics

  1. jQuery is a library of javascript functions that you can use in your code. If you know the basics of javascript then you will be able to easily learn jQuery. 
  2. You can very easily apply different operations and formatting on different tags in your html code. For ex: If you want to hide a specify elements(lets say <p>) upon click a link. You can easily do this via jQuery. 
  3. To use jQuery you have to find the tag(selector) on which you have to perform the action. Basic syntax is:
    1. $(selector).action(
      1. To access jQuery library $ is used. We can use jQuery in place of $. At some places we do use jQuery instead of a $, we will explore it in more details at later point in the tutorial. 
      2. A (selector) or tag in the html document. 
      3. action() specifies the operation to be performed on the selected tag.
  4. There are certain ways to find the html element. These methods are similar to finding elements in CSS.
    1. $(“h1”) - This method will select the element h1.
    2. $(“#format”) - This method will select the element whose id=“format” in the html page.
    3. $(“.formatter”) - This method will select the element whose class = “formatter” in the html element. 
  5. To use jQuery library you can either download it and include it your source code. Or else you can refer it from its hosted location. One such location is: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
  6. Hence you should include this library reference in the script tag like this:
    1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
  7. And it should be included in your head tag like this:
    1. <head>
    2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    3. </head>
  8. Quick Notes:
    • jQuery uses $ sign as a shortcut for jQuery
    • jQuery is Client side scripting
  9. What if other JavaScript frameworks also use the $ sign as a shortcut?
  10. If two different frameworks are using the same shortcut, one of them might stop working.
    The jQuery team have already thought about this, and implemented the noConflict() method.
    The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
    $.noConflict();
    jQuery(document).ready(function(){
      jQuery("button").click(function(){
        jQuery("p").text("jQuery is still working!");
      });
    });


jQuery Events

jQuery Mouse Events
Some of the jQuery methods are common and can be executed on desired tags. All the methods attaches the event handlers on the html element on which they are attached. Once that action is performed the event handler is called and it performs the set of steps on the corresponding html element. 
  1. .click() - Action is performed when html tag/selector is clicked.
  2. .dblclick() - Action is performed when html tag/selector is double clicked
  3. .focus() - Action is performed when html/tag selector is focused on.
  4. .change() - Action is performed when html tag/selector value changes. It is limited to tags: <input>, <textarea>, <select>
  5. .mouseenter() - Action is performed when mouse enters the html tag/selector. 
  6. .mouseleave() - Performs opposite action as compared to mouse enter.
  7. .hover() - Perform action when mouse is hovered over the corresponding html tag/selector.
  8. .focusout() - Event is executed when the focus moves away from corresponding html tag/selector.
  9. .mousedown() - Event is executed when mouse button is clicked on the html tag/selector.
  10. .mousemove() - Event is executed when mouse move in the html tag/selector.
  11. .mouseout() - Event is executed when mouse moves out of the html element. 
  12. .mouseover() - Event is executed when mouse moves over the html element. 
  13. .mouseup() - Event is executed when mouse is over the html element and is released. 
  14. .toggle() - This event is deprecated in the jQuery 1.8. 

jQuery Keyboard events:
  1. .focusout() - Event is invoked when any element or an element below it loses focus. It is different from blur since it supports losing focus from the child elements.
  2. .keydown() - Event is invoked when any key is pressed. Any element in focus will receive the actions when this event is executed. 
  3. .keypress() - Similar to keydown but following keys will not register key press event: shift, Del, Esc
  4. .keyup() - Event is invoked when a key is released.Because of event bubbling all the key presses will be propagated to the document element. For specific elements, we can use .keypress().

Document Rendering Events:
    • .load() - Action is performed when html tag/selector is loaded.
    • .ready() - Action is performed when the DOM is ready or the document is ready. It doesn’t work well with .load since that operation will start performing its operation as soon as the element is available. However, .ready is not going to execute its action till entire DOM is available. When this function is called then we should use $.noConflict() to avoid the namespace conflicts and we have to use jQuery in place of $. 
    • .unload() - Action to be performed when the user intends to go away from the page. The action of going away include:
      • - click on forward and back button.
      • - Refresh a page
      • - clicking on exit browser button. 

Keyboard Events:
    • 1) .focusout() - Event is invoked when any element or an element below it loses focus. It is different from blur since it supports losing focus from the child elements.
    • 2) .keydown() - Event is invoked when any key is pressed. Any element in focus will receive the actions when this event is executed. 
    • 3) .keypress() - Similar to keydown but following keys will not register key press event: shift, Del, Esc
    • 4) .keyup() - Event is invoked when a key is released.Because of event bubbling all the key presses will be propagated to the document element. For specific elements, we can use .keypress().

Commonly Used jQuery Event Methods
    • $(document).ready(): The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.
    • click()
      • The click() method attaches an event handler function to an HTML element.
      • The function is executed when the user clicks on the HTML element.
    • dblclick()
      • The dblclick() method attaches an event handler function to an HTML element.
      • The function is executed when the user double-clicks on the HTML element:
    • mouseenter()
      • The mouseenter() method attaches an event handler function to an HTML element.
      • The function is executed when the mouse pointer enters the HTML element:
    • mouseleave()
      • The mouseleave() method attaches an event handler function to an HTML element.
      • The function is executed when the mouse pointer leaves the HTML element:
    • mousedown()
      • The mousedown() method attaches an event handler function to an HTML element.
      • The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:
    • mouseup()
      • The mouseup() method attaches an event handler function to an HTML element.
      • The function is executed, when the left mouse button is released, while the mouse is over the HTML element:
    • hover()
      • The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
      • The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:
    • focus()
      • The focus() method attaches an event handler function to an HTML form field.
      • The function is executed when the form field gets focus:
    • blur()
      • The blur() method attaches an event handler function to an HTML form field.
      • The function is executed when the form field loses focus:


jQuery DOM Manipulation: One very important part of jQuery is the possibility to manipulate the DOM. jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes
    • text() - Sets or returns the text content of selected elements
    • html() - Sets or returns the content of selected elements (including HTML markup)
    • val() - Sets or returns the value of form fields
    • The jQuery attr() method is used to get attribute values.


Call back functions

$("#btn1").click(function(){
    $("#test1").text(function(i,origText){
        return "Old text: " + origText + " New text: Hello world!
        (index: " + i + ")"; 
     });
 });
We can have similar callback functions for the other methods: text, html, val
  • remove() - Removes the selected element (and its child elements)
  • empty() - Removes the child elements from the selected element

Call Back Function example:
$("#div1").remove();
$("p").remove(".italic");


jQuery Methods


  • jQuery addClass() Method
The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:
Example
$("button").click(function(){
    $("h1,h2,p").addClass("blue");
    $("div").addClass("important");
});

  • jQuery removeClass() Method
The following example shows how to remove a specific class attribute from different elements:
Example
$("button").click(function(){
    $("h1,h2,p").removeClass("blue");
});

  • jQuery toggleClass() Method
The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:
Example
$("button").click(function(){
    $("h1,h2,p").toggleClass("blue");
});

  • Set a CSS Property
$("p").css("background-color","yellow");


  • Set Multiple CSS Properties
$("p").css({"background-color":"yellow","font-size":"200%"});


  • jQuery Dimension Methods
jQuery has several important methods for working with dimensions:
    • width()
    • height()
    • innerWidth()
    • innerHeight()
    • outerWidth()
    • outerHeight()

  • Traversing Up the DOM Tree
Three useful jQuery methods for traversing up the DOM tree are:
    • parent(): The parent() method returns the direct parent element of the selected element. And it goes up only a single level.
    • parents(): Find all the parents.
    • parentsUntil(): Find the parents till a specific html or class or id specified
$(document).ready(function(){
     $("span").parentsUntil("div");
});


  • Traversing Down the DOM Tree
Two useful jQuery methods for traversing down the DOM tree are:
    • children()
    • find()
The children() method returns all direct children of the selected element and it traverses only a single level down. 

The find() method returns descendant elements of the selected element, all the way down to the last descendant.
$(document).ready(function(){
     $("div").find("span");
});

  • Traversing Sideways in The DOM Tree
    • siblings(): Returns all the siblings of the current element. 
    • next()
    • nextAll()
    • nextUntil()
    • prev()
    • prevAll()
    • prevUntil()

  • jQuery prev(), prevAll() & prevUntil() Methods
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).
JQuery Filtering
The first() method returns the first element of the selected elements.


  • jQuery + Ajax: 
<script>
$(document).ready(function(){
    $("button").click(function(){
       $("#div1").load("demo_test.txt");
  });
});
</script>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>


  • jQuery load() Method
The load() method loads data from a server and puts the returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);
- The required URL parameter specifies the URL you wish to load.
- The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
- The optional callback parameter is the name of a function to be executed after the load() method is completed.
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});
</script>


  • jQuery $.get() Method
The $.get() method requests data from the server with an HTTP GET request.
Syntax:
$.get(URL,callback);
$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});


  • jQuery $.post() Method
The $.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

There are many other popular JavaScript frameworks like: Angular, Backbone, Ember, Knockout, and more.


Basic Code Snippets
Get Text:
$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

Set Text:
$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});

Get Html:
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

Set Html:
$("#btn2").click(function(){
  $("#test2").html("<b>Hello world!</b>");
});

Get Value:
$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

Set Value: 
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

Get Value:
$("button").click(function(){
  alert($("#w3s").attr("href"));
});

Set Value:
$("button").click(function(){
  $("#w3s").attr("href","http://www.w3schools.com/jquery");
});

$("button").click(function(){
  $("#w3s").attr({
    "href" : "http://www.w3schools.com/jquery",
    "title" : "W3Schools jQuery Tutorial"
  });
});


NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...