J Query
J Query
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)
The following figure shows which DOM elements will be returned from
$('p') & $'(div').
jQuery Selectors Demo
As you can see in the above figure, $('div') will return all the <div>
elements including its child elements.
Select Elements by Id
The following figure shows which DOM elements will be returned from
$('#myDiv1') & $'(#prg2').
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>
Try it
In the following example, jQuery returns all the elements that have
class or contenteditable attribute irrespective of any value.
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>
Try it
Method Description
The following figure shows how the DOM manipulation methods add
new elements.
Syntax:
$('selector expression').after('content');
Syntax:
$('selector expression').before('content');
Syntax:
$('selector expression').append('content');
Syntax:
$('selector expression').prepend('content');
Syntax:
$('selector expression').remove();
Syntax:
$('content string').replaceAll('selector expression');
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).
The following table lists all the jQuery methods to get or set DOM
element's dimensions.
jQuery Method Description
offset() Get or set left and top coordinates of the specified element(s).
innerWidth() Get or set the inner width (padding + element's width) of the
specified element(s).
Syntax:
$('selector expression').height(value);
Syntax:
$('selector expression').width(value);
Syntax:
$('selector expression').offset(options);
Points to Remember :
jQuery dimension methods allows you to manipulate dimensions
of DOM elements.
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.
jQuery Events
You will learn about jQuery events in this section.
The following table lists all jQuery methods and corresponding DOM
events.
change onchange
focus onfocus
focusin onfocusin
select onselect
submit onsubmit
keypress onkeypress
keyup onkeyup
focusout
dblclick ondblclick
focusout
hover
mousedown onmousedown
mouseenter onmouseenter
mouseleave onmouseleave
mousemove onmousemove
mouseout onmouseout
mouseover onmouseover
mouseup onmouseup
Toggle
Resize onresize
Scroll onscroll
Unload onunload
Event Handling
To handle DOM events using jQuery methods, first get the reference of
DOM element(s) using jQuery selector and invoke appropriate jQuery
event method.
Event Object
Hover Events
Internally all of the shorthand methods uses on() method. The on()
method gives you more flexibility in event binding.
Syntax:
on(types, selector, data, fn )
● Types = One or more space-separated event types and optional
namespaces
● Selector = selector string
● Data = data to be passed to the handler in event.data when an event
is triggered.
● Fn = A function to execute when the event is triggered.
You can use selector to filter the descendants of the selected elements
that trigger the event.
Try it
You can create separate functions and specify that as a handler. This is
useful if you want to use the same handler for different events or
events on different elements.
Try it
Event Bubbling
The following example demonstrates event bubbling in jQuery.
Example:Event Bubbling
$('div').click(function (event) { alert( event.target.tagName +
' clicked'); }); <div> <p> <span>This is span.</span> </p>
</div>
Try it
As you can see in the above example, we have handled click event of
<div> element in jQuery. So if you click on div, it will display alert
message 'DIV clicked'. However, if you click on span, still it will popup
alert message SPAN clicked even though we have not handled click
event of <span>. This is called event bubbling. Event bubbles up to
the document level in DOM hierarchy till it finds it.
Visit event methods reference to know about all the event methods in
jQuery.
Points to Remember :
The jQuery event methods allow you to attach event handler or
fire native DOM events.
Use the selector to get the reference of an element(s) and then
call jQuery event methods to fire it or attach an event handler.
Important DOM manipulation methods: click(), dblClick(),
change(), submit(), keyup(), keydown(), mouseenter(),
mouseleave(), hover() etc.
Syntax:
$.ajax(url);
$.ajax(url,[options]);
Parameter description:
● url: A string URL to which you want to submit or retrieve the data
● options: Configuration options for Ajax request. An options
parameter can be specified using JSON format. This parameter is
optional.
The following table list all the options available for configuring Ajax
request.
Options Description
accepts The content type sent in the request header that tells the server
what kind of response it will accept in return.
dataType The type of data that you're expecting back from the server.
jsonpCallback String containing the callback function name for a JSONP request.
type A type of http request e.g. POST, PUT and GET. Default is GET.
Let's see how to send http requests using $.ajax() (or jQuery.ajax())
method.
The following example shows how to get the JSON data using ajax()
method.
In the above example, first parameter is a request url which will return
JSON data. In the options parameter, we have specified dataType and
timeout options. The dataType option specifies the type of response
data, in this case it is JSON. The timeout parameter specifies request
timeout in milliseconds. We have also specified callback functions for
error and success.
The ajax() method returns an object of jQuery XMLHttpRequest. The
following example shows how to use jQuery XMLHttpRequest object.
So this way you can send GET, POST or PUT request using ajax()
method.
Syntax:
$.get(url, [data],[callback]);
Parameters Description:
● url: request url from which you want to retrieve the data
● data: data to be sent to the server with the request as a query
string
● callback: function to be executed when request succeeds
The following example shows how to retrieve data from a text file.
The following example shows how to retrieve JSON data using get()
method.
Syntax:
$.getJSON(url,[data],[callback]);
Parameter Description:
● url: request url from which you want to retrieve the data
● data: JSON data to be sent to the server as a query string
● callback: function to be executed when request succeeds
The second parameter is data to pass as query string with the GET
request. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve
Internally, jQuery getJSON() method calls get() method and set
dataType to JSON. Visit james.padolsey.com/jquery and search for get()
method to see the source code.
You can attach fail and done callback methods to getJson() method as
shown below.
Syntax:
$.getScript(url, [callback]);
Parameter Description:
● url: request url from which you want to download JavaScript file
● callback: function to be executed when request succeeds
The following example shows how to download script file using
getScript() method.
Thus, you can use different get methods to retrieve different types of
resources using http get request.
Points to Remember :
$.get(), $.getJSON() method allows you to send asynchronous
http GET request to retrieve the data from the server without
reloading whole page.
$.get() can be used to retrieve any type of response from the
server.
$.getJSON() method is a short form method to retrieve JSON
response from the server.
$.getScript() sends asynchronous http GET request to retrieve
the script files from the server and execute it.
Syntax:
$.get(url,[data],[callback])
$.getJSON(url,[data],[callback])
$.getScript(url,[callback])
Syntax:
$.post(url,[data],[callback],[type]);
Parameter Description:
● url: request url from which you want to submit & retrieve the
data.
● data: json data to be sent to the server with request as a form
data.
● callback: function to be executed when request succeeds.
● type: data type of the response content.
Let's see how to submit data and get the response using post()
method. Consider the following example.
The following example shows how to submit and retrieve JSON data
using post() method.
You can also attach fail and done callback methods to post() method
as shown below.
Points to Remember :
$.post() method allows you to send asynchronous http POST
request to submit and retrieve the data from the server without
reloading whole page.
Syntax:
$.post(url,[data],[callback],[type])
Specify type parameter for the type of response data e.g.
specify 'JSON' if server return JSON data.
Internally post() method calls ajax() method only by passing
method='POST' as option.
Syntax:
$.load(url,[data],[callback]);
Parameters Description:
● url: request url from which you want to retrieve the content
● data: JSON data to be sent with request to the server.
● callback: function to be executed when request succeeds
The following example shows how to load html content from the server
and add it to div element.
In the above example, we have specified html file to load from the
server and add its content to the div element.
Note : If no element is matched by the selector then Ajax request will not be
sent.
demo.html content:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <title></title> </head> <body> <h1>This is demo html
page.</h1> <div id="myHtmlContent">This is my html
content.</div> </body> </html>
Points to Remember :
$.load() method allows HTML or text content to be loaded from
a server and added into a DOM element.
Syntax:
$.post(url,[data],[callback])
Specify selector with url to specify a portion of the response
document to be inserted into DOM element.
$('#msgDiv').load('/demo.html #myHtmlContent');