-
Notifications
You must be signed in to change notification settings - Fork 1
3. jQuery
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. jQuery is the most popular JavaScript library in use today, with installation on 65% of the top 10 million highest-trafficked sites on the Web. jQuery is free, open-source software licensed under the MIT License. Check here in wiki
The slogan of jQuery is write less, do more. With jQuery, we can write less lines of code comparing to writing the same function with pure Javascript. There are many out-of-box APIs we can use to create different kinds of animations or build complex Ajax applications. jQuery also has high capabilities allowing developers to create plug-ins on the top of it. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The Developers can build powerful web applications with jQuery's powerful extensibility.
As we all known, jQuery is a Javascript Library which make Javascript easier be written. So we still need to have some basic ideas about Javascript. There are a lot of people discussing whether start learning javascript first or jQuery. Some people supported javascript because jQuery base on it and the other said learning jQuery because its simplicity. From my point of view, However, for people who want to learn jQuery, the basic knowledge of javascript is necessary. You don't have to be a javascript expert before starting practicing jQuery. So in this tutorial, we will introduce the basic concept of javascript.
JavaScript is an object oriented dynamic language with types and operators, standard built-in objects, and methods. Every type has its specific behaviors and operations. There are six basic types:
- Number
- String
- Boolean
- Object
- Function
- Array
- Date
- RegExp
- null
- undefined
Type number is, literally, a type for numbers. In C language, we classify number into int, long, double, float and so on. Different types define different range of numerical value. For example, int represents the integer number between -2^15+1 to 2^15-1. long is the integer number between -2^31+1 to 2^31-1. float represents the floating point number in the range from 1.8E-38 to 3.4E+38. In Javascript, However, it summarizes all these numerical types into one Type called number.
We can test the following lines below:
>> typeof 0.002
>> typeof 3.13e10
We can get the same results:
<< number
In C, we call a single word char (characters) and words as "str" (string). Javascript is a lazier language and it combines them into 1 type named "String". When we declare the a string type value, we have to wrap the words with quote symbols (" ").
>> typeof "apple"
<< "string"
Bolean represents true or false. In numerical expression, we can use 1 to represent the true and 0 for false.
>> typeof true
<< "boolean"
>> 1 == true
<< true
>> 0 == false
<< true
Object contains several subtypes including Function, Array, Date and Regular Expression.(Discussing those types later)
null and undefined are two odd value for representing None. The differences between are: Null represents empty or void value; undefined means the variables are not assigned any value. Simply to say, null is a value and undefined is a default value for variables which are not assigned.
>> var test
<< undefined
>> test = null /** Assign a null value to test variable **/
<< null /** test now has a null value **/
We use keyword var to declare variables.
>> var variable1;
>> variable1
<< undefined /* The default value for an undefined variable is "undefined" */
>> var variable2 = "This is a variable.";
>> variable2;
<< "This is a variable."
Variables have their own existence area depending on the living scopes they have. If we declare a variable outside from any functions or loops. It becomes a global variable. Once a global variable is created, it will be attached to window object.
>> var t = "testing";
>> window.t
<< "testing"
By the way, we don't have to type window always for calling global variables. Instead, type the variable name only is acceptable.
We can call global variable from everywhere:
>> t
<< "testing"
>> (function() {console.log(t);})(); /* Create an anonymous function which executes instantly */
<< "testing"
>> function addStringtoT() { t += " testing"; } /* Declare a function to append more testing*/
>> addStringtoT() // Make a function call for executing.
>> t
<< "testing testing"
It looks like global variables are really handy for usage and calling. But why do many skillful programmers discourage about using global variables? When we just write a little script as I did above, the mini script does not take many variables. However, in reality, we will write thousand lines of code and we have to declare huge numbers of variables. Global variables conflict with other variables easily if their name are not unique enough and these conflicts will somehow increase the difficulty for debugging. Unless we can promise that the namespace we give to the global variable are 100% unique, we can use them for sure.
There are other shortcomings of global variables. For further details, you can read this article.
Local variables are always declared under the function scope. In other words, the variables will only exist when those functions are called and run.
>> (function() {var innerT = "local variable testing";})();
/* Declare an innerT variable within the function scope*/
>> innerT // Call it outside the function
<< ReferenceError: innerT is not defined // An error pops out.
If you have the experience on programming C, you know that the variables created inside the loop only living in the loop scope. Let's test whether the javascript has the same feature or not.
>> for (var i = 0; i <= 100; i++) { var a = "t"; } /* A variable "a" will be created iteratively. */
>> a // Call "a" outside the for scope
>> "t"
What?! "a" becomes a global variable? Trust your eyes, it is one of the javascript features: there is no block scope. Only function scope is available in Javascript.
Conditional statements allow programs to do specific functions according to the condition they encounter.
There are two conditional statements in Javascript. The first one is if..else and the other is switch statement.
If there are two conditions (Yes or No) to check, we can write the if statement as below:
if (condition 1) {
... /* Program Operation with condition 1 */
} else {
... /* Program condition not follow */
}
If we need to identify more than two conditions, we can write multiple if statements:
if (condition 1) {
... /* Program Operation with condition 1 */
} else if (condition 2) {
... /* Program condition with condition 2 */
} else if (condition 3) {
... /* Program condition with condition 3 */
}
...
} else {
... /* Program for the last condition */
}
Copy the following snippet for testing:
>> function testCondStats(cond) {
if (cond === 1) {
console.log("This is the first condition.");
} else if (cond === 2) {
console.log("The is the second condition.");
} else {
console.log("This is the rest condition");
}
}
Start the tests:
>> testCondStats(2)
<< The is the second condition.
>> testCondStats(3)
<< This is the rest condition
There are another conditional statement call switch which can deliver the same effect as If...else... statement.
The switch syntax is:
switch (expression) {
case value1:
//Statements executed when the result of expression matches value1
[break;]
case value2:
//Statements executed the result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the result of expression matches valueN
[break;]
default:
//Statements executed when none of the values match the value of the expression
[break;]
}
So we can rewrite the "if..else..." test snippet:
>> function testCondStats(cond) {
switch(cond) {
case 1:
console.log("This is the first condition.");
break;
case 2:
console.log("This is the second condition.");
break;
default:
console.log("This is the rest condition");
}
}
>> testCondStats(1)
<< This is the first condition
>> testCondStats(1000)
<< This is the rest condition
Switch is not designed for other logical operators such as "<", ">", "<=" and ">=". Instead it checks the condition only with equal operator (expression === valueN). However we can use logical operators still (check here) but not recommended.
Ternary is a shorthand of if ... else ... statement. Here is the syntax:
condition ? expr1 : expr2
The meaning of the above statement is: if the condition's result is true, executes the expr1; if it is false, then executes the expr2.
>> ~~(true) === 1 ? "Yes": "None";
<< "Yes"
>> "Is PI bigger than 4? " + (Math.PI > 4? "Yes": "No")
<< "Is PI bigger than 4? No"
Multiple ternary operators are acceptable too:
>> function isBrotherhoodMember(gender, age) { return gender === "female" ? false: age >= 20 ? true: false }
/* A brotherhood is recruiting the new member with the conditions: 1. Not a female. 2. Older than 20. */
<< isBrotherhoodMember("male", 1000)
>> true
<< isBrotherhoodMember("male", 1)
>> false
<< isBrotherhoodMember("mxale", 1) // "mxale" is a typo. lol
>> false
<< isBrotherhoodMember("female", 20)
>> false
Doing multiple operations in each case is fine with ternary operator:
>>
Why does human rely on computers to do complex computation? Because computers are good at doing one thing again and again without any mistakes. Looping allows computers iterate the operations thousand of times. There are three looping structures in Javascript. One is for, another is while and the other is do...while.
Here is the statement:
for ([initialization]; [condition]; [final-expression]) {
....
statements
....
}
initialization: Typically used to initialize a counter variable. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. condition: An expression to be evaluated before each loop iteration. If the result of evaluation is true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, the iteration is over and move to the statement following to the loop structure. final-expression: An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable. statement: A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).
Let's test a loop with empty statement:
>> for (var i = 0; i <= 100000; i++);
>> i
<< 100001
A for loop with single statement:
>> for (var i = 0; i < 100; i++) console.log(i);
<< 0
<< 1
<< 2
...
<< 99
A for loop with multiple statements:
>> var test = "";
>> for (var i = 0; i<= 100; i++) { console.log(test); test += i.toString() + ", "; }
<< 0,
<< 0, 1,
....
<< "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, "
>> test
<< "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, "
While statement looks like:
while (condition) {
statement
}
While loop executes when the condition evaluates to true. Unlike for loop, there is no final-expression block for increment or decrement at each iteration. We often write the increment or decrement statement inside the while loop.
>> var j = 0;
>> while(j < 1000) { console.log(j); j+=2; }
<< 0
<< 2
<< ...
<< 1000
The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
>> var j = 100;
>> do { console.log(--j); } while( j > 0 )
<< 99
...
<< 0
>> j
<< 0
In javascript, function is an object.(There is no class in JS)
The below is the definition about DOM from MDN:
"The Document Object Model (DOM) is a programming interface for HTML, XML and SVG documents. It provides a structured representation of the document (a tree) and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects that have properties and methods. Nodes can also have event handlers attached to them, and once that event is triggered the event handlers get executed. Essentially, it connects web pages to scripts or programming languages.
Though often accessed using JavaScript, the DOM itself is not a part of the JavaScript language, and it can be accessed by other languages, though this is much less common."
Simply to say, DOM makes the document structured with Object-Oriented. Every element inside the document has its own properties and functions. Also, there are relative relation between different elements such as parent and children representing the inheritance relationship.
The magics that Javascript created are mostly based on the DOM. Hence, the concept of DOM plays an important role for developing the web services.
Go to jQuery's official site to download the jQuery file. There are two versions: one starts with prefix "1" and another starts with "2". The differences are the previous one supports older IE which make its size larger and the later one is lighter owing to the elimination of the old IE support. If you want to learn the source code, download the uncompressed one. Want to go production? Please get the compressed one or use CDN.
After the download, we can import jQuery with script tag like below: (Better Practice)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
</body>
</html>
Or (Not recommended):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
</head>
<body>
</body>
</html>
We import jQuery at then bottom of the body. Why don't we just import it in the head? Because this way is helpful for performance. We all know that the browsers read the code line by line. Put the javascript on the head will make those javascript be compiled before rendering other HTML elements. As long as a user open a web page, they can't see the html elements unless the whole javascript are compiled inside head tag. In contrast, if we put the javascript at the bottom, users will see the html elements first and javascript functions will be executed after the page rendering is completed. Truth be told: No matter where you put your javascript code, the total consuming time is the same. However, users decide the speed of page according to the time they wait for page displayed. Let them see the page first will put them under an illusion about high performance. In fact, there are thousand lines of javascript code running secretly which they don't know about.
In some cases, we might want to put the javascript functions in the head to let them run before the html elements rendering. But it is not so often.
In this section, we want to show how jQuery does DOM querying (Traversing). After we import jQuery successfully, it's time to write simple jQuery code for querying.
jQuery's basic syntax:
jQuery("css selectors")
or $("css selectors")
.
The meaning of the above syntax is: Selecting the elements with selector and referencing them with jQuery functions.
The $ symbol has the same meaning with jQuery. Here is the source code in jQuery.js:
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
Of course, we can not fully understand the code's meaning, but we can know somehow that the $ is equal to jQuery.
Let's open queryFromDOM.html to play jQuery!
We can put html tag inside the parenthesis as $("body")
to query the body element and it will return the body object.
[<body>…</body><div id="id1" class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><script type="text/javascript" src="jquery-2.1.4.min.js"></script></body>]
Class name is also available. For example, $(".test")
will return every element with test class in array:
[<div id="id1" class="test"></div>, <div class="test"></div>, <div class="test"></div>, <div class="test"></div>, <div class="test"></div>]
Selecting item with id is easy. $("#id1")
returns the element with id name "#id1": [<div id="id1" class="test"></div>]
More Complex CSS selectors are acceptable too. We can input $("div.test ul li")
and the output is what we expect for: [<li>This is for testing.</li>, <li>This is for testing.</li>, <li>This is for testing.</li>]
. It is easy but we have a better practice by typing $("div.test ul").children("li")
and we will get the same result as the former did. children()
is a jQuery function to call the selected elements' children.
Why did I say the latter one is a better practice? Because Reference an element with jQuery functions is costly on memory usage. We had better reduces the time for referencing objects with jQuery. The first one will select three objects and reference them with jQuery functions. In contrast, the later only does reference once and make a function call to get its children. Please remember this function in the mind always.
jQuery provides many functions for querying DOM:
children("CSS selector")
can find the children following the defined rules. If it is empty in parenthesis, it select all children of the nodes.
Empty example:
>> $("div.container").children() /* Get all children not matter what */
<< [<div id="id1" class="header test"></div>, <div class="main test">…</div>, <div class="footer"></div>]
With CSS Selector:
>> $("div.container").children(".test") /* Select children with test class */
<< [<div id="id1" class="header test"></div>, <div class="main test">…</div>]
Not only children can be traversed, but also parents can be. parents()
returns the whole ancestors and parent()
just return the closest one called parent.
>> $("div.main-row").parents()
<< [<div class="main test">…</div>, <div class="container">…</div>, <body>...</body>, <html>...</html>]
>> $("div.main-row").parent()
<< [<div class="main test">…</div>]
In a family, we have parents, children, brothers and sisters. Does jQuery provide a function to call my brothers and sisters? Of course, it provides function sibling()
to fulfill our need.
>> $("div.main").siblings()
<< [<div id="id1" class="header test"></div>, <div class="footer"></div>]
find("CSS selector")
can find the element by specific selector under the chosen DOM.
>> $("div.container").find("div.main-row")
<< [<div class="main-row test">…</div>, <div class="main-row test">…</div>, <div class="main-row test">…</div>]
Sometimes we just want to get the first element following the selection rule. first()
can make it deliver.
>> $("div.main-row").first()
<< <div class="main-row test"><h3>The first heading</h3></div>
The is a function last()
for the last element as well.
>> $("div.main-row").last()
<< <div class="main-row test">
<h3>The third heading</h3>
...
</div>
Function next()
returns the element next to the selected.
>> $("div.header").next() /* Choose the element next to the header */
<< <div class="main test"> ... </div>
On the other hand, the function prev()
get the element before it.
>> $("div.footer").prev()
<< <div class="main test"> ... </div>
We can querying DOM to get elements we want with jQuery but it's not enough for developing dynamic web pages. We usually want to create new elements and put the on the page or remove the elements from the page. As one of the most popular javascript libraries in the world, jQuery takes care of every aspect of developers' need. Create and delete operations are truly handy with jQuery.
.append(element object)
can attach an element to the defined location.
>> var e = document.createElement("p"); /* Create a p html element */
>> $("div.main-row").append(e) /* Attach the "p" to all the "div.main-row" elements */
<< [<div class="main-row test">...<p></p></div>, <div class="main-row test">...<p></p></div>, <div class="main-row test">...<p></p></div>] /* Return those receive the "p" elements successfully. */
Unlike .append()
function, appendTo(location)
append the elements in reverse way. .append()
let the selected node append the new and appendTo
points the node where the new should attach to.
>> var e = document.createElement("p");
>> $("div.main-row").append(e)
<< [<p></p>, <p></p>, <p></p>] /* Display the elements attached successfully. */
We can put the elements by relative position. To put elements before another, there are two functions we can apply: .before()
and .insertBefore
. With .before()
, the content to be inserted comes from the method's argument.
>> var e = document.createElement("h1")
>> e.textContent = "This heading is before header"; /* Setup the content for h1 element */
>> $("div.header").before(e)
<< [<div id="id1" class="header test"></div>] // The element is inserted successfully.
.insertBefore()
the location be inserted comes from the arguments inside.
>> var e = document.createElement("h1")
>> e.textContent = "This heading is before header"; /* Setup the content for h1 element */
>> $(e).insertBefore("div.header")
<< [<div id="id1" class="header test"></div>] /* Get the same result as before did */
For moving elements after others, we can use after()
and insertAfter()
. They are similar as what before-related functions have done.
Let's try .after()
first:
>> var e = document.createElement("h1")
>> e.textContent = "This is after the footer."
>> $("div.footer").after(e)
<< [<div class="footer"></div>]
.insertAfter()
can do the same job:
>> var e = document.createElement("h1")
>> e.textContent = "This is after the footer."
>> $(e).insertAfter("div.footer")
<< [<div class="footer"></div>]
jQuery allows developers to query DOM in easy way and also gives developers API to manipulate the nodes' CSS properties. Open the jQueryCSS.html to try the below functions.
.addClass("classname")
adds the classname to the DOM.
>> $("div.main").find(".test").first().addClass("active")
/* Add the "active" class to the element */
<< [<div class="main-row test active"></div>]
Now we can see the first element turns red.
.haveClass("classname")
checks whether the class of node is existed or not. If the wanted class is existed, then returns true; if not, returns false.
>> $("div.main").hasClass("test")
<< false
>> $("div.main").find(".test").hasClass("test")
<< true
.css()
can display the chosen CSS property's value:
>> $("div.main").css("display")
<< "block"
.css()
can display multiple CSS properties:
>> $("div.main").css(["display", "font-size", "height", "width"]) /* List the wanted properties with an Array */
<< Object {display: "block", font-size: "16px", height: "304px", width: "1214px"}
We can use .css()
to set CSS property:
>> $("div.main").css("height", "1000px")
<< <div class="main" style="height: 1000px;">...</div> /* Return the adjusted result. */
>> $("div.main").css("height") /* Reconfirm the Result */
<< "1000px"
Using .css()
to set up multiple properties are available:
>> $("div.main").find(".test").first().css({"backgroundColor": "blue", "height": "100px" })
<< <div class="main-row test" style="height: 100px; background-color: blue;"></div>
>> $("div.main").find(".test").first().css("backgroundColor");
<< "rgb(0, 0, 255)"
>> $("div.main").find(".test").first().css("height");
<< "100px"
.height()
can let we know the element's height.
>> $("div.main").children().first().height()
<< 300
We can use height()
to set the element's height.
>> $("div.main").children().first().height(100)
<< <div class="main-row test" style="height: 100px;"></div>
.innerHeight()
is the padding top, padding bottom and original height combined.
>> $("div.main").children().first().innerHeight()
<< 320
Just like .height()
, the .innerHeight()
can be used for setting.
>> $("div.main").children().first().innerHeight(600) /* The combined height equals to 600px */
<< <div class="main-row test" style="height: 580px;"></div>
/* The padding is "10px 20px", so the total height is "10px + 580px + 10px" */
.outerHeight()
has a winder range. It counts the border width and the margin.
>> $("div.main").children().first().outerHeight()
<< 340
Like the others, .outerHeight() allows developers to set up the height value.
>> $("div.main").children().first().outerHeight(1000)
<< <div class="main-row test" style="height: 960px;"></div>
The reason we learn javascript is to design web pages with dynamic effects.