This is a quick, rough tutorial (It can contain mistakes)
I) jQuery selectors & jQuery Cheat Sheet:
-------------------------------------------------------------
Look at the Table here:
http://stevewellens.xtreemhost.com/jQuerySelectorTester.htm
Some points (to be read with the table in above link as reference) -
1. jQuery selectors are placed within single quotes.
E.g.
i. $('#myid')
ii. $('[id=myid]')
iii. $('[id="my id"]') - Double quotes are needed if there is a whitespace in the value of the attribute
2. Return value of a 'jQuery selector' is usually an array of elements
except when we use shortcuts like # and . shortcuts
E.g. $('#myid') and $('.myCSSclass')
3. Most important selector to know:
$('element[attribute="value"]')
E.g. $('input[id="abc"]') - select all 'input' tags with "abc" as their ids.
Note - this returns an array of elements; to use only one,
we have to use the 0th index one -
E.g. $('input[id="abc"]')[0].hide()
Since selecting an element based on its 'id' attribute is probably the most commonly used selector,
jQuery has a shortcut for it - using #
E.g. $('#abc') or $('input#abc')
Note - this is not just a shortcut for the syntax; this returns only 1 element
(If there are multiple elements with the same 'id', it returns the 1st one)
II) Most Commonly used jQuery statements:
------------------------------------------------------------
0. Selecting elements using substring-of-their-id/name
$('#abc') - an element with id as 'abc'
$('[id^="abc"]') - array of elements with id starting with 'abc'
$('[id$="abc"]') - array of elements with id ending with 'abc'
$('[id*="abc"]') - array of elements with id containing 'abc'
1. Hide/Show an element
$('#abc').hide()
$('#abc').show()
2. Get html contained within a div
$('#abc').html()
3. Replace html within a div with some other html (contained within a string)
var str_html = " This is going to be the new content";
$('#abc').html(str_html)
4. Change a CSS attribute - use css(attribute_name, attribute_value)
$('#abc').css("color","red")
5. Add/Remove a CSS class - especially useful when using Bootstrap
$('#abc').addClass("myClass")
$('#abc').removeClass("myClass")
6. Find 'parent', 'siblings'
$('#abc').parent()
$('#abc').siblings()
III) functions in javascript
-----------------------------------
Functions in Javascript can be passed as values to other functions.
This is typically used w.r.t Event Handlers & Callbacks (to ajax calls)
Supposed we want some code to be executed when an event happens;
we wrap that code with the 'function' keyword and curly {} braces, and
pass that as an argument to the event-handler
E.g. 1: Event handlers example
------
Suppose we have a textbox , and we want to show an alert message when a key is pressed inside the textbox:
Option A:
---------
function showMessage() {
alert('key has been pressed');
}
$('#abc').mousedown(showMessage);
Option B: (more commonly used)
---------
$('#abc').mousedown(function() {
alert('key has been pressed');
});
Note:
1. in B, the entire code of the function has been passed like a value
2. in B, the function does not have a name
3. We would typically use Option A if code reuse is going to there,
otherwise we would go with option B.
Option B is more commonly seen in jQuery code.
E.g 2: Callback to Ajax request example:
------
Suppose we have a ajax call that returns json data:
$.getJSON('/get_users_list', function(response) {
});
IV) $(array).each & 'this' keyword
------------------------------------------------------
jQuery provides a way to iterate over an array - using 'each'
When using 'each', 'this' will refer to the indiviual item of the array
E.g. 1:
-------
var arr = ["abc", "pqr", "xyz"];
$(arr).each(function() {
var item = this;
alert(item);
});
E.g. 2:
-------
Suppose a Ajax request to /getMoviesList returns
{"items":[
{"movieID":"65086","title":"The Woman in Black","poster":"\/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"},
{"movieID":"76726","title":"Chronicle","poster":"\/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"}
]}
and we want to iterate over the above result;
Observe that "items" is an array , so essentially we want to iterate over "items" array
var users_array = response.items;
$(users_array).each(function() {
var movie_record = this;
alert(movie_record.movieID);
alert(movie_record.title);
});
});
I) jQuery selectors & jQuery Cheat Sheet:
-------------------------------------------------------------
Look at the Table here:
http://stevewellens.xtreemhost.com/jQuerySelectorTester.htm
Some points (to be read with the table in above link as reference) -
1. jQuery selectors are placed within single quotes.
E.g.
i. $('#myid')
ii. $('[id=myid]')
iii. $('[id="my id"]') - Double quotes are needed if there is a whitespace in the value of the attribute
2. Return value of a 'jQuery selector' is usually an array of elements
except when we use shortcuts like # and . shortcuts
E.g. $('#myid') and $('.myCSSclass')
3. Most important selector to know:
$('element[attribute="value"]')
E.g. $('input[id="abc"]') - select all 'input' tags with "abc" as their ids.
Note - this returns an array of elements; to use only one,
we have to use the 0th index one -
E.g. $('input[id="abc"]')[0].hide()
Since selecting an element based on its 'id' attribute is probably the most commonly used selector,
jQuery has a shortcut for it - using #
E.g. $('#abc') or $('input#abc')
Note - this is not just a shortcut for the syntax; this returns only 1 element
(If there are multiple elements with the same 'id', it returns the 1st one)
II) Most Commonly used jQuery statements:
------------------------------------------------------------
0. Selecting elements using substring-of-their-id/name
$('#abc') - an element with id as 'abc'
$('[id^="abc"]') - array of elements with id starting with 'abc'
$('[id$="abc"]') - array of elements with id ending with 'abc'
$('[id*="abc"]') - array of elements with id containing 'abc'
1. Hide/Show an element
$('#abc').hide()
$('#abc').show()
2. Get html contained within a div
$('#abc').html()
3. Replace html within a div with some other html (contained within a string)
var str_html = " This is going to be the new content";
$('#abc').html(str_html)
4. Change a CSS attribute - use css(attribute_name, attribute_value)
$('#abc').css("color","red")
5. Add/Remove a CSS class - especially useful when using Bootstrap
$('#abc').addClass("myClass")
$('#abc').removeClass("myClass")
6. Find 'parent', 'siblings'
$('#abc').parent()
$('#abc').siblings()
III) functions in javascript
-----------------------------------
Functions in Javascript can be passed as values to other functions.
This is typically used w.r.t Event Handlers & Callbacks (to ajax calls)
Supposed we want some code to be executed when an event happens;
we wrap that code with the 'function' keyword and curly {} braces, and
pass that as an argument to the event-handler
E.g. 1: Event handlers example
------
Suppose we have a textbox , and we want to show an alert message when a key is pressed inside the textbox:
Option A:
---------
function showMessage() {
alert('key has been pressed');
}
$('#abc').mousedown(showMessage);
Option B: (more commonly used)
---------
$('#abc').mousedown(function() {
alert('key has been pressed');
});
Note:
1. in B, the entire code of the function has been passed like a value
2. in B, the function does not have a name
3. We would typically use Option A if code reuse is going to there,
otherwise we would go with option B.
Option B is more commonly seen in jQuery code.
E.g 2: Callback to Ajax request example:
------
Suppose we have a ajax call that returns json data:
$.getJSON('/get_users_list', function(response) {
});
IV) $(array).each & 'this' keyword
------------------------------------------------------
jQuery provides a way to iterate over an array - using 'each'
When using 'each', 'this' will refer to the indiviual item of the array
E.g. 1:
-------
var arr = ["abc", "pqr", "xyz"];
$(arr).each(function() {
var item = this;
alert(item);
});
E.g. 2:
-------
Suppose a Ajax request to /getMoviesList returns
{"items":[
{"movieID":"65086","title":"The Woman in Black","poster":"\/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"},
{"movieID":"76726","title":"Chronicle","poster":"\/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"}
]}
and we want to iterate over the above result;
Observe that "items" is an array , so essentially we want to iterate over "items" array
$.getJSON('/getMoviesList', function(response) {var users_array = response.items;
$(users_array).each(function() {
var movie_record = this;
alert(movie_record.movieID);
alert(movie_record.title);
});
});
See http://stackoverflow.com/questions/9450083/using-each-within-getjson for related code
V) $(document).ready event
-------------------------------------
Suppose we want some code to be executed when the page finishes loading,
we could -
1. wrap that code with 'function' keyword & curly {} braces, and
2. specify that code as part of $(document).ready event-handler.
E.g. 1. Suppose we want to show an alert message when page finishes loading
$(document).ready(function() {
alert("page has finished loading");
});
E.g. 2. Suppose we want to attach an event-handler to a button's click event,
we have 2 options -
Option A:
---------
we have to make sure to place the code (that attaches the event-handler to the button) after the button tag itself
<button id="btn1">Button 1</button>
$('#btn1').click(function() {
alert("button 1 has been clicked");
});
Note - the Javascript code that acts on the button, has to appear after the button's html
Option B:
---------
we could place the javascript code within $(document).ready's event-handler;
then, the code will run after the entire page loads, which should mean that the button has been created also
(so that there would be no danger of trying to access the button before it gets created)
$(document).ready(function() {
$('#btn1').click(function() {
alert("button 1 has been clicked");
});
});
IMPORTANT - We can have as many $(document).ready event-handlers we want;
this is probably the main difference between window.onload & $(document).ready event-handlers.
VI) Finding elements within elements
-------------------------------------------------
1. > and space operators in specifying hierarchy
> operator : search only immediate children
E.g
$('#abc > div') - returns all div elements that are immediate children of #abc
space operator: search children, grand-children, great-grand-children, and so on
E.g.
$('#abc td') - returns all td elements that can occur anywhere within #abc
2. find() method
Another syntax we can use instead of the space operator above is via find() method
$('#abc td')
$('#abc').find('td')
VII) jQuery chaining
----------------------------
Most function calls do some operation on the selected html-elements, and then return the array of selected html-elements,
so that chaining-of-methods is possible.
E.g. $('#abc').show().css("border-color","red");
Exceptions - functions like .html() and .text() return strings, so chaining is not possible with these methods
VIII) jQuery and dynamically added elements
-------------------------------------------------------------
This is one of the most common hard-to-find problem when using jQuery.
If we have code to attach event-handlers within $(document).ready event, we have to remember that $(document).ready event
only fires once (and all its event-handlers are executed only once) as soon as the page finishes loading.
After that, if we have javascript code that creates new html elements, then , by default , those new elements will not
get event-handlers specified in $(document).ready event;
In order to solve this problem, jQuery has given the .on() method;
.on() method allows us to specify event-handlers for elements that can be created in the future also
This usually comes into the picture when we are using .html() method to create new elements, or when we want
to attach event-handlers to 3rd part widgets that keep manipulating their html a lot
Documentation - http://api.jquery.com/on/
IX) $.ajax(), $.getJSON(), and 'async' attribute
---------------------------------------------------------------
$.ajax() - method to make Ajax calls
$.getJSON() - shortcut form of $.ajax() wherein we get JSON data as result
async - when using $.ajax(), we can specify async: false (default value is true)
- this means that we want the ajax call to Not-be asynchronous, i.e we want a synchronous operation
- this is not that commonly used, but if we have more than 1 ajax call within the same function,
we have to keep this in mind
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.getJSON/
X) General Javascript headaches
---------------------------------------------
1. When page is loading, if there is a javascript error on a particular line of code, subsequent lines of code are
not executed.
2. Cross-domain Ajax requests from the browser are not allowed
XI) Tools to use:
----------------------
1. jsFiddle, jsbin.com
2. Chrome Developer Tools
- Inserting Breakpoints is a mess (this is better in Firefox, but interface for Firebug has changed recently, and is sometimes unreliable)
Thanks ra, Anna.
ReplyDeleteThank you sai garu(legend)....:):):)
ReplyDelete