jQuery : Basics

jQuery is a free open source javascript library which greatly simplifies javascript programming. It works across browsers allowing you to concentrate on end result. Some of the important core features of jQuery – DOM manipulation, event handling, ajax support, animation, etc. Finally it is extensible, i.e you can use various third party plugins to perform specialize tasks, or write your own.

jQuery comes in 2 verion – Production version (compressed and minified) and the development version. I will be using jQuery 1.11.1 development version. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8. You can download jQuery from its official site and put in your js folder and refer it in your html. You can also use CDN for including jQuery to your website.

Lets write a simple jQuery enable page. first.html:


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Page</title>
<script type="text/javascript" src="../../js/jquery-1.11.1.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#myid").html("Lets start with JQuery");
});

</script>
</head>
<body>
<div id="myid"></div>
</body>
</html>

post0_first

As you can see I have downloaded the jQuery lib and kept in the js folder. If you don’t want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network like google –  “http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js&#8221; ) and include it.

$ is just a function. It is actually an alias for the function called jQuery. This function is heavily overloaded and means different things depending on what arguments it is passed.

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

$(document).ready(function(){ /*SomeCode*/} is used to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section. Notice that we are passing an anonymous fuction to the ready method that will get executd once the DOM has finished loading.

The traditional way for the same to be achieved is write somefunction() and assign it to windows.onload=somefunction(). The problem with this is that the onload even only fires after all the page content has been downloaded, including images. It is also harder to add mulitple independent onload functions. jQuery actually allows you to run when the DOM of the page is ready regardless whether the content has been downloaded or not. Also, you can call documet.ready function multiple times, and jQuery will chain together each one to be called in succession.

Selectors and Filters

jQuery slectors and filters retrive content from the document so it can be manipulated using other function. It returns an array of objects that matches the slection criteria and filter will further refine it. This array is not DOM elements, rathers its a collection of jQuery object that are wrapped around DOM elements and provide a large number of predefine functions for further operating on the object.

Selector Description
tagname Find all elements that are named tagname.
#identifier Find all elements with ID as identifier
.className Find all elements having class attribute named className.
tag#id.className Retrieves all tag elements having ID as id and class attribute as className.

The above are the basic selection in jQuery. You can select elements based on heirarchical relationships or on a series of common criteria.

Selector Description
selector1,selector2.. Find all elements with specfied selectors
.class1.class2 Find all elements with both .class1 and .class2 applied.
parent > child Find all child elements that are direct children of elements of type parent.
prev + next Find all next elements that are next to a prev element.
prev ~ siblings Find all sibiling elements thta come after prev and match the sibilings selector.

Lets see this by an example.- selectors1.html


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Selectors</title>
<script type="text/javascript" src="../../js/jquery-1.11.1.js"></script>
<script>
$(document).ready(function(){
 $("p").css("border","2px solid green");
 });
</script>
</head>
<body>
<h2 class="h">Heading</h2>
<p class="a">This is a paragraph 0.</p>
<p>This is another paragraph 1.</p>
<p class="a">This is another paragraph 2.</p>
<p class="b" id="para3">This is another paragraph 3.</p>

<ul>
<li class="a">Item 0</li>
<li>Item 1</li>
<li class="b">Item 2</li>
</ul>
</body>
</html>

 

 

The above jquery will select all p elemets.

post0_selectors11

Try the following, one line at a time for further understanding:


$("p.b, li.b").css("border","2px solid green"); //selects all p and li elements having class b - para 3 and Item 2
$("ul li.a").css("border","2px solid green"); //selects all li elements under ul having class a - Item 0
$("h2 + p").css("border","2px solid green"); //select paragraph that is next to h2 - para 0
 $("h2 ~ *").css("border","2px solid green"); //select all elemets that are sibiling to h2 - all para and ul

You can refine a selector by including elements that match certain conditions, indexs etc.

Filter Description
:first Select only the first instance of the selectors returned set.
:last Select only the last instance of the selectors returned set.
:even Select only the even instance of the selectors returned set.
:eq(n) Filter out elemets that are positioned at the given index
:gt(n) Includes elements are are past the given indexs.
:not(selector) Include elemets that do not match the given selector.

Try the following one at time .


$("p:first").css("border","2px solid green"); //selects only the first para - para 0
$("p:even").css("border","2px solid green"); //selects only even para - para 0 and 2
$(".b:first").css("border","2px solid green"); //selects all elements having class b and then return first - para 3
$("p:gt(1)").css("border","2px solid green"); //selects p elemets having index greater that 1 - para 2 and 3
$("p:not(p:eq(1))").css("border","2px solid green"); //selects p elemets except index 1 - para 0,2,3

Attribute filters – You can filter the result of a selector statement based on attribute content

Filter Description
[attribute] Include elements in the result if they have specified attribute.
[attribute=value] Include elements in the result if they have specified attribute with a specific value.
[attribute!=value] Include elements in the result if they have specified attribute which doesnt have this value.
[attribute^=value] Include elements in the result if they have specified attribute and it starts with a specific value.
[attribute$=value] Include elements in the result if they have specified attribute and it ends with a specific value.
[attribute*=value] Include elements in the result if they have specified attribute and it contains a specific value.
[attributeFilter1][attributeFilter2] Include elasdasdemets that do not match the given selector.

Test following one line at a time


$("p[class]").css("border","2px solid green"); //selects p having atrribute class - para 0,2,3
$("p[class=a]").css("border","2px solid green"); //selects p having atrribute class which is a - para 0,2
$("p[id$=3]").css("border","2px solid green"); //selects p elements whose id ends with 3 - para 3
$("[id*=para]").css("border","2px solid green"); //selects p elements whose id contains para - para 1,3

Content and Visibility filters – These can also be use to refine your query

Content Filter Description
:contains[text] Filter the selection to only include elements that contain the text string.
:empty Filter only if the elements are empty.
:has(selector) Mathches elements that contains at least one element that has the specified selector.
:parent Matches all elements that are parents(i.e they contain at least one othe element, including text)

 

Visibility  Filter Description
:visible Filter the selection to only include visisble elements.
:hidden Filter the selection to only include hidden elements.

Child filters – Based on parent relationship

Child Filter Description
:nth-child(index)
:nth-child(even)
:nth-child(odd)
:nth-child(equation)
Matches to elements at index,even,odd or a equation of the form Xn+M like 3n, 3n+1.
:first-child Matches to elements who are first child of their parents.
:last-child Matches to elements who are last child of their parents.
:only-child Matches to elements who are only child of their parents.

$("p:contains(3)").css("border","2px solid green"); //selects p which contains the text 3 - para 3
$("ul:has(li[class=a])").css("border","2px solid green"); //selects the ul (not li), if any if its li elements has class a
$("ul li:nth-child(2n+1)").css("border","2px solid green"); //selects li inside ul which satisfy 2n - Item 0, 1

Form Selectors –  are used for form elements.

Form selectors Description
:input All input elements
:text All input elements with type=”text”
:password All input elements with type=”password”
:radio All input elements with type=”radio”
:checkbox All input elements with type=”checkbox”
:submit All input elements with type=”submit”

These are some of the selectors and filters that are commonly used. You can go through the full list from API.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: