Lec #4 Jquery Intro New

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

DCIT 50 – Object-Oriented Programming hayperaktib

Lecture # 1 jQuery Introduction + Event Binding

jQuery Introduction
The purpose of jQuery is to make it much easier to use JavaScript on your website.

What You Should Already Know


Before you start studying jQuery, you should have a basic knowledge of:
 HTML
 CSS
 JavaScript

What is jQuery?

jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and
DOM manipulation.

The jQuery library contains the following features:


 HTML/DOM manipulation  Effects and animations
 CSS manipulation  AJAX
 HTML event methods  Utilities

Why jQuery?

There are lots of other JavaScript frameworks out there, but jQuery seems to be the most
popular, and also the most extendable.

Many of the biggest companies on the Web use jQuery, such as:
 Google  IBM
 Microsoft  Netflix

Adding jQuery to Your Web Pages


There are several ways to start using jQuery on your web site. You can:
 Download the jQuery library from jQuery.com
 Include jQuery from a CDN, like Google

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on


the element(s).

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

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements

1
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

The Document Ready Event

You might have noticed that all jQuery methods in our examples, are inside a document ready
event:

$(document).ready(function(){

   // jQuery methods go here...

});

This is to prevent any jQuery code from running before the document is finished loading (is
ready).

jQuery Selectors

In this section, you will learn about jQuery selectors and how to find DOM element(s) using
selectors.

The jQuery selector enables you to find DOM elements in your web page. Most of the times you
will start with selector function $() in the jQuery.

Syntax:
$(selector expression, context)

jQuery(selector expression, context)


The selector expression parameter specifies a pattern to match the elements. The jQuery
uses CSS selector patterns as well as its own pattern to match the elements.

The context parameter is optional. It specifies elements in a DOM hierarchy from where
jQuery starts searching for matching elements.

Let's see commonly used selectors in jQuery.

Select elements by name:

The most common selector pattern is element name. Specifing an element name as string e.g. $
(‘p’) will return an array of all the <p> elements in a webpage.
The following figure shows which DOM elements will be returned from $('p') & $(‘div').

2
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

jQuery Selectors Demo

As you can see in the above figure, $('div') will return all the <div> elements including
its child elements.

Example: Select elements by name

$('p').append('This is paragraph.'); // appends text to all p elements

$('div').append('This is div.); // appends text to all div elements

<div>
<p></p>
<p></p>
</div>
<p></p>
<div></div>

Select elements by id:

jQuery append() method inserts text at the end in the element.


You can get a particular element by using id selector pattern. Specify an id of
an element for which you want to get the reference, starting with # symbol.

The following figure shows which DOM elements will be returned from $('#myDiv1') &
$'(#prg2').

3
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

jQuery Id Selector Demo

Example: Select element by #Id

$('#impPrg').append('This element\'s id is "impPrg"');

$('#myDiv2').append('This element\'s id is "myDiv2"');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg"></p>

<div id="myDiv2">
</div>

Select elements by attribute:


jQuery also allows you to find an element based on attributes set on it. Specifing an
attribute name in square brackets in $ function e.g. $('[class]') will return all the
elements that have class attribute irrespective of value.

In the following example, jQuery returns all the elements that have class or contenteditable
attribute irrespective of any value.

4
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

jQuery Attribute Selector

Example: Select elements by attribute

$('[class]').append('This element has class attribute');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg" class="boldPrg"></p>


<div id="myDiv2" class="yellowDiv">
</div>
You can also specify a specific value of an attribute in attribute selector. For example, $
('[class="myCls"]') will return all the elements which have class attribute with myCls as a
value.

jQuery Selector by Attribute Value

Example: Select element by attribute value

$('[class="yellowDiv"]').append('This element includes class="yellowDiv" attribute');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg" class="boldPrg">This is paragraph.</p>

<div id="myDiv2" class="yellowDiv">


</div>

jQuery Selector Patterns:

5
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

jQuery provides number of ways to select a specific DOM element(s). The following table
lists the most important selector patterns.

Category Selector Description

Find by $('p') Find all <p> elements


Element

$('p, div, code') Find <p>,<div> and <code> elements

Find $('div p') Find all <p> elements which are


Descendant descendants of <div>
Elements

$('div > p') Find <p> which is child of <div>

$(*) Find all elements

Find by Id $('#myDiv') Find element whose id is myDiv

$('p#myPrg') Find <p> element whose Id is myPrg

$('#myDiv1, #myDiv2') Find multiple elements by id separated by


comma.

Find by CSS $('.myCSSClass') Find all the elements


Class with class=myCSSClass.

$('.myCSSClass1, .myCSSClass2 ') Finds all elements whose class attribute


is set to myCSSClass1 or myCSSClass2

$('div.myCSSClass') Finds all <div> elements


with class=myCSSClass

$('p:first-child') Find all <p> elements, which is the first


child of its parent element. (parent
element can be anything)

Find by $('[class]') Find all the elements with


Attributes the classattribute(whatever the value).

6
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Category Selector Description

$('div[class]') Find all the <div> elements that have


a class attribute(whatever the value).

Find by $('div[class=myCls]') Find all the <div> elements whose class


containing attributes are equal to myCls.
value of
attribute

$('div[class|=myCls]') Find all the <div> elements whose class


attributes are either equal to myCls or
starting with myCls string followed by a
hyphen (-).

$('div[class *="myCls"]') Selects <div> elements whose class


attributes contain myCls.

$('div[class~=myCls]') Selects div elements whose class


attributes contain myCls, delimited by
spaces.

$('div[class$=myCls]') Selects <div> elements whose class


attributes value ends with myCls. The
comparison is case sensitive.

$('div[class!=myCls]') Selects <div> elements which does not


have class attribute or value does not
equal to myCls.

$('div[class^=myCls]') Selects <div> elements


whose class attribute value starts with
myCls.

$ Find all <div> elements that contains the


('div:contains("tutorialsteacher")' text 'tutorialsteacher'

Find by Input $(":button") Find all input whose type is button.


type

$(':input[type="radio"]') Find all radio input types.

Even-Odd rows $('tr:odd') Find all odd rows. (1,3,5,7..)

7
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Category Selector Description

$('tr:even') Find all even rows.(0,2,4,6..)

jQuery Methods

You learned about jQuery selectors in the previous section. The jQuery selector finds
particular DOM element(s) and wraps them with jQuery object. For example,
document.getElementById() in the JavaScript will return DOM object whereas $('#id') will
return jQuery object. The following figure illustrates the difference.

jQuery Methods
As you can see in the above figure, document.getElementById function returns div element
whereas jQuery selector returns jQuery object which is a wrapper around div element. So now,
you can call jQuery methods of jQuery object which is returned by jQuery selector.

jQuery provides various methods for different tasks e.g. manipulate DOM, events, ajax etc.
The following table lists different categories of methods.

Category Description Imp Methods

DOM These methods manipulate DOM elements in some after(),append(),


Manipulation manner e.g. changing attribute, style attr(),before(),
attribute, adding and removing elements etc. more..

Traversing These methods help in navigating from DOM children(),closest(),


element to another element in a parent child each(),first(),next(),

8
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Category Description Imp Methods

hierarchy e.g. finding ancestors, descendants filter(),parent(),


or sibling element of a specified element. siblings(),
more..

CSS These methods get and set css related addClass(),css(), 


properties of elements. hasClass(),removeClass(),
toggleClass()
more..

Attributes These methods get and set DOM attributes of attr(),html(),removeAttr(), 


elements. prop(), val(), 
more..

Events These methods are used to handle DOM or bind(),blur(), change(), 


JavaScript events. click(), dblclick(),focus(),
keyup(),keydown(),
more..

Effects These methods are used to add animation to animate(),fadeIn(),fadeOut(),


elements. hide(),show(),stop(),more..

Dimensions These methods are used to get and set the CSS height(),width(),innerHeight(),
dimensions for the various properties. innerWidth(),more..

Forms These methods and event handlers handle forms blur(),change(),val(),submit(),


and their various elements. more..

Ajax These methods allow Ajax functionalities with get(),getJson(),post(),load(),


jQuery e.g. more..

Core These methods are core methods in jQuery API. jQuery(),holdReady(),when(),


more..

Data These methods allow us to associate arbitrary data(),removeData(),queue(),


data with specific DOM elements. dequeue(),clearQueue(),
more..

Miscellaneous These methods are useful in various tasks each(),index(),get(),


e.g. traversing elements, converting to array toArray(),more..
etc.

9
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Category Description Imp Methods

Utilities Utility methods are helpful in getting inArray(),isArray(),


information on various things e.g. browser, isFunction(),isNumeric(),
function, array, window etc. isWindow(),isXmlDoc(),
more..

10
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

The following example shows how to use some of the jQuery methods to manipulate DOM
elements.

jQuery methods Example:

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="~/Scripts/jquery-2.1.3.js"></script>
<script type="">
$(document).ready(function () {

$('p').wrap('<div class="myCls">'); @* wrap all p with div *@


$('#myDiv').hide(); @* hides div whose id is myDiv *@
$('span').attr({
'color': 'red',
'width': '100%'
});
$('p').append('This is p.'); @* append text to <p> *@

$('span').before('<p>This is another p</p>'); @* insert <p> before span *@

});
</script>
</head>

<body>
<div id="myDiv"></div>
<p></p>
<span></span>
</body>
</html>

DOM Manipulation Methods in jQuery:

jQuery provides various methods to add, edit or delete DOM element(s) in the HTML page.

The following table lists some important methods to add/remove new DOM elements.

Method Description

append() Inserts content to the end of element(s) which is specified by a selector.

before() Inserts content (new or existing DOM elements) before an element(s) which is
specified by a selector.

11
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Method Description

after() Inserts content (new or existing DOM elements) after an element(s) which is
specified by a selector.

prepend() Insert content at the beginning of an element(s) specified by a selector.

remove() Removes element(s) from DOM which is specified by selector.

replaceAll( Replace target element(s) with specified element.


)

wrap() Wrap an HTML structure around each element which is specified by selector.

The following figure shows how the DOM manipulation methods add new elements.

DOM Manipulation Methods


Let's have a quick overview of important DOM manipulation methods.

jQuery after() method:


The jQuery after() method inserts content (new or existing DOM elements) after target
element(s) which is specified by a selector.

Syntax:
$('selector expression').after('content');
First of all, specify a selector to get the reference of target element(s) after which you
want to add the content and then call after() method. Pass the content string as a
parameter. Content string can be any valid HTML element.

Example: jQuery after() method

12
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

$('#div1').after('<div style="background-color:yellow"> New div </div>');

<div id="div1">div 1
</div>

<div id="div2">div 2
</div>

Output:

<div id="div1">div 1
</div>

<div style="background-color:yellow"> New div </div>

<div id="div2">div 2
</div>

jQuery before() method:


The jQuery before() method inserts content (new or existing DOM elements) before target
element(s) which is specified by a selector.

Syntax:
$('selector expression').before('content');
Specify a selector to get the reference of target element(s) before which you want to add
the content and then call before() method. Pass the content string that can be any valid
HTML element as parameter.

Example: jQuery before() method

$('#div1').before('<div style="background-color:yellow"> New div </div>');

<div id="div1">div 1
</div>

<div id="div2">div 2
</div>

Output:
<div style="background-color:yellow"> New div </div>
<div id="div1">div 1
</div>

13
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

<div id="div2">div 2
</div>

jQuery append() method:


The jQuery append() method inserts content to the end of target element(s) which is
specified by a selector.

Syntax:
$('selector expression').append('content');
First specify a selector expression to get the reference of an element(s) to which you want
to append content, then call append() method and pass content string as a parameter.

Example: jQuery append() method

$('p').append('World!');

<p>Hello </p>

Output:
<p>Hello World!</p>

jQuery prepend() method:


The jQuery prepend() method inserts content at the beginning of an element(s) specified by a
selector.

Syntax:
$('selector expression').prepend('content');
First specify a selector expression to get the reference of an element(s) to which you want
to prepend the content, then call prepend() method and pass content string as a parameter.

Example: jQuery prepend() method

$('div').prepend('<p>This is prepended paragraph</p>');

<div>
<label>This is div.</label>
</div>

Output:
<div>
<p>This is prepended paragraph</p>
<label>This is div.</label>
</div>

jQuery remove() method:


The jQuery remove() method removes element(s) as specified by a selector.

14
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Syntax:
$('selector expression').remove();
First specify a selector expression to get the reference of an element(s) which you want to
remove from the document and then call remove() method.

15
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Example: jQuery remove() method

$('label').remove();

<div>This is div.
<label>This is label.</label>
</div>

Output:
<div>
This is div.
</div>

jQuery replaceAll() method:


The jQuery replaceAll() method replaces all target elements with specified element(s).

Syntax:
$('content string').replaceAll('selector expression');
Here, syntax is different. First specify a content string as replacement element(s) and then
call replaceAll() method with selector expression to specify a target element(s).

Example: jQuery replaceAll() method

$('<span>This is span</span>').replaceAll('p');

<div>
<p>This is paragraph.</p>
</div>

<p>This is another paragraph.</p>

Output:
<div>
<span>This is span</span>
</div>
<span>This is span</span>

jQuery wrap() method:


The jQuery wrap() method wrap each target element with specified content element.

Syntax:
$('selector expression').wrap('content string');
Specify a selector to get target elements and then call wrap method and pass content string
to wrap the target element(s).

Example: jQuery wrap() method

16
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

$('span').wrap('<p></p>');

<div>
<span>This is span.</span>
</div>
<span>This is span.</span>

Output:
<div>
<p> <span>This is span.</span></p>
</div>
<p><span>This is span.</span></p>
Manipulate HTML Attributes using jQuery:

The following table lists jQuery methods to get or set value of attribute, property, text or
html.

jQuery Method Description

attr() Get or set the value of specified attribute of the target element(s).

prop() Get or set the value of specified property of the target element(s).

html() Get or set html content to the specified target element(s).

text() Get or set text for the specified target element(s).

val() Get or set value property of the specified target element.

The following figure shows various jQuery methods to access DOM element's attributes,
properties and values.

17
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

jQuery methods to access element's values


Let's have a quick overview of important methods to access element's attributes.

jQuery attr() method:


jQuery attr() method is used to get or set the value of specified attribute of DOM element.

Syntax:
$('selector expression').attr('name','value');
First of all, specify a selector to get the reference of an element and call attr() method
with attribute name parameter. To set the value of an attribute, pass value parameter along
with name parameter.

Example: jQuery attr() method

$('p').attr('style'); // returns "font-size:16px;font-weight:bold"


$('div').attr('class','yellowDiv'); // adds class='divCls' to each div element

<div>
This is div.
</div>
<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
<div>
This is div.
</div>
<p>
This is paragraph.
</p>

In the above example, $(‘p’).attr(‘style’) gets style attribute of first <p> element in a
html page. It does not return style attributes of all the <p> elements.

jQuery prop() method:

18
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

The jQuery prop() method gets or sets the value of specified property to the DOM element(s).

Syntax :
$('selector expression').prop('name','value');
First of all, specify a selector to get the reference of an element(s) and call prop()
method. Supply "name" parameter to get the value of that property. To set the value of a
property, specify a value parameter along with name parameter.

Example: jQuery prop() method

var style = $('p').prop('style');


style.fontWeight; // returns "bold"

$('div').prop('class','yellowDiv'); // add class="yellowDiv" to all div elements

<div>
This is div.
</div>
<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
<div>
This is div.
</div>
<p>
This is paragraph.
</p>

In the above example, $(‘p’).prop(‘style’) returns an object. You can get different style
properties by using object.propertyName convention e.g. style.fontWeight. Do not include '-'
as a property name.

jQuery html() method:


The jQuery html() method gets or sets html content to the specified DOM element(s).

Syntax:
$('selector expression').html('content');
First of all, specify a selector to get the reference of an element and call html() method
without passing any parameter to get the inner html content. To set the html content,
specify html content string as a parameter.

Example: jQuery html() method

$('#myDiv').html(); //returns innerHtml of #myDiv

//add <p>This is paragraph.</p> to #emptyDiv


$('#emptyDiv').html('<p>This is paragraph.</p>');

<div id="myDiv" class="yellowDiv">


<p style="font-size:16px;font-weight:bold">
This is paragraph.

19
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

</p>
</div>
<div id="emptyDiv">
</div>

jQuery text() method


The jQuery text() method gets or sets the text content to the specified DOM element(s).

Syntax:
$('selector expression').text('content');
First of all, specify a selector to get the reference of an element and call text() method
to get the textual content of an element. To set the text content, pass content string as a
parameter.

20
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Example: jQuery text() method

$('#myDiv').text(); //returns "This is paragraph."


$('p').text(); //returns "This is paragraph."

//removes all the content from #emptyDiv and inserts "This is some text." to it
$('#emptyDiv').text('This is some text.');

<div id="myDiv" class="divCls">


<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
</div>
<div id="emptyDiv">
</div>

Please note that text() method only returns text content inside the element and not the
innerHtml.

jQuery val() method:

The jQuery val() method gets or sets value property to the specified DOM element(s).

Syntax:
$('selector expression').val('value');
First of all, specify a selector to get the reference of an element and call val() method to
get the value of value property. To set the text content, pass content string as a
parameter.
Example: jQuery val() method

$('input:Submit').val(); //returns "Save"

//set value of input text to "Steve"


$('input:text').val('Steve');

$('input:text').val(); //returns "Steve"

<div>
<label>Name:</label><input type="text" />
</div>

<div>
<input type="Submit" value="Save" />
</div>

In the above example, val() method returns value of "value" property. If element does not
support value property then val() method returns null.

Manipulate DOM Element's Dimensions using jQuery:

The jQuery library includes various methods to manipulate DOM element's dimensions like
height, width, offset, position etc.

21
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

The following table lists all the jQuery methods to get or set DOM element's dimensions.

jQuery
Method Description

height() Get or set height of the specified element(s).

innerHeight( Get or set inner height (padding + element's height) of the specified
) element(s).

outerHeight( Get or set outer height (border + padding + element's height) of the specified
) element(s).

offset() Get or set left and top coordinates of the specified element(s).

position() Get the current coordinates of the specified element(s).

width() Get or set the width of the specified element(s).

innerWidth() Get or set the inner width (padding + element's width) of the specified
element(s).

outerWidth() Get or set outer width (border + padding + element's width) of the specified
element(s).

The following figure shows various dimensions of an element.

22
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

DOM Element's Dimensions

jQuery height() method:


The jQuery height()method gets or sets height of the specified DOM element(s).

Syntax:
$('selector expression').height(value);
Specify a selector to get the reference of an element and call height() method to get the
height in pixel. To set the height of specified elements, specify height as integer
parameter in height() method.

Example: jQuery height() method

$('#myDiv').height(); //returns height of #myDiv in pixels


$('p').height(); //returns height in pixel

//set height of all div elements


$('div').height(100);

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

jQuery width() method:

23
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

The jQuery width() method gets or sets width of the specified DOM element(s).

Syntax:
$('selector expression').width(value);
Specify a selector to get the reference of an element and call width() method to get the
width in pixel. Specify width as integer parameter to set the width.

Example: jQuery width() method

$('#myDiv').width(); //returns width of #myDiv in pixels


$('p').width(); //returns width of p in pixel

//set width of all div elements


$('div').width(100);

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

jQuery offset() method:


The jQuery offset() method gets or sets coordinates of the specified element(s).

Syntax:
$('selector expression').offset(options);
Specify a selector to get the reference of an element and call offset() method to get the
jQuery object which has left and top property. Specify JSON object with left and top
property with the coordinates where you want to move the element.

Example: jQuery offset() method

var ofs = $('#myDiv').offset();


alert('left:' + ofs.left + ', top: ' + ofs.top);

$('p').offset({ left:100, top:200});

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

24
DCIT 50 – Object-Oriented Programming hayperaktib
Lecture # 1 jQuery Introduction + Event Binding

Points to Remember :

1. jQuery dimension methods allows you to manipulate dimensions of DOM elements.


2. Use the selector to get the reference of an element(s) and then call jQuery dimension
methods to edit it.

Important DOM manipulation methods: height(), width(), offset(), position() etc.

25

You might also like