CSS Drop Down Menu

Wednesday, 11 December 2013

JQuery



JQuery

 Introduction

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
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

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

Downloading jQuery

There are two versions of jQuery available for downloading:
  • Production version - this is for your live website because it has been minified and compressed
  • Development version - this is for testing and development (uncompressed and readable code)
Both versions can be downloaded from jQuery.com.
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>

 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
  • 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".
This is 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.
Here are some examples of actions that can fail if methods are run before the document is fully loaded:
  • Trying to hide an element that is not created yet
  • Trying to get the size of an image that is not loaded yet
·         Tip: The jQuery team has also created an even shorter method for the document ready event:
·         $(function(){

   // jQuery methods go here...

});

jQuery Selectors

jQuery selectors are one of the most important parts of the jQuery library.
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector

The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
$("p")

Example
When a user clicks on a button, all <p> elements will be hidden:

Example

$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").hide();
  });
});
</script>
</head>

<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>

The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the element:
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:

Example

$(document).ready(function(){
  $("button").click(function(){
    $("#test").hide();
  });

The .class Selector

The jQuery class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:

Example

$(document).ready(function(){
  $("button").click(function(){
    $(".test").hide();
  });
});

 

jQuery Selectors

Selector
Example
Selects
*
$("*")
All elements
#id
$("#lastname")
The element with id="lastname"
.class
$(".intro")
All elements with class="intro"
.class,.class
$(".intro,.demo")
All elements with the class "intro" or "demo"
element
$("p")
All <p> elements
el1,el2,el3
$("h1,div,p")
All <h1>, <div> and <p> elements



:first
$("p:first")
The first <p> element
:last
$("p:last")
The last <p> element
:even
$("tr:even")
All even <tr> elements
:odd
$("tr:odd")
All odd <tr> elements



:first-child
$("p:first-child")
All <p> elements that are the first child of their parent
:first-of-type
$("p:first-of-type")
All <p> elements that are the first <p> element of their parent
:last-child
$("p:last-child")
All <p> elements that are the last child of their parent
:last-of-type
$("p:last-of-type")
All <p> elements that are the last <p> element of their parent
:nth-child(n)
$("p:nth-child(2)")
All <p> elements that are the 2nd child of their parent
:nth-last-child(n)
$("p:nth-last-child(2)")
All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n)
$("p:nth-of-type(2)")
All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n)
$("p:nth-last-of-type(2)")
All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child
$("p:only-child")
All <p> elements that are the only child of their parent
:only-of-type
$("p:only-of-type")
All <p> elements that are the only child, of its type, of their parent



parent > child
$("div > p")
All <p> elements that are a direct child of a <div> element
parent descendant
$("div p")
All <p> elements that are descendants of a <div> element
element + next
$("div + p")
The <p> element that are next to each <div> elements
element ~ siblings
$("div ~ p")
All <p> elements that are siblings of a <div> element



:eq(index)
$("ul li:eq(3)")
The fourth element in a list (index starts at 0)
:gt(no)
$("ul li:gt(3)")
List elements with an index greater than 3
:lt(no)
$("ul li:lt(3)")
List elements with an index less than 3
:not(selector)
$("input:not(:empty)")
All input elements that are not empty



:header
$(":header")
All header elements <h1>, <h2> ...
:animated
$(":animated")
All animated elements
:focus
$(":focus")
The element that currently has focus
:contains(text)
$(":contains('Hello')")
All elements which contains the text "Hello"
:has(selector)
$("div:has(p)")
All <div> elements that have a <p> element
:empty
$(":empty")
All elements that are empty
:parent
$(":parent")
All elements that are a parent of another element
:hidden
$("p:hidden")
All hidden <p> elements
:visible
$("table:visible")
All visible tables
:root
$(":root")
The document’s root element
:lang(language)
$("p:lang(de)")
All <p> elements with a lang attribute value starting with "de"



[attribute]
$("[href]")
All elements with a href attribute
[attribute=value]
$("[href='default.htm']")
All elements with a href attribute value equal to "default.htm"
[attribute!=value]
$("[href!='default.htm']")
All elements with a href attribute value not equal to "default.htm"
[attribute$=value]
$("[href$='.jpg']")
All elements with a href attribute value ending with ".jpg"
[attribute|=value]
$("[title|='Tomorrow']")
All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value]
$("[title^='Tom']")
All elements with a title attribute value starting with "Tom"
[attribute~=value]
$("[title~='hello']")
All elements with a title attribute value containing the word "hello"
[attribute*=value]
$("[title*='hello']")
All elements with a title attribute value containing the string "hello"



:input
$(":input")
All input elements
:text
$(":text")
All input elements with type="text"
:password
$(":password")
All input elements with type="password"
:radio
$(":radio")
All input elements with type="radio"
:checkbox
$(":checkbox")
All input elements with type="checkbox"
:submit
$(":submit")
All input elements with type="submit"
:reset
$(":reset")
All input elements with type="reset"
:button
$(":button")
All input elements with type="button"
:image
$(":image")
All input elements with type="image"
:file
$(":file")
All input elements with type="file"
:enabled
$(":enabled")
All enabled input elements
:disabled
$(":disabled")
All disabled input elements
:selected
$(":selected")
All selected input elements
:checked
$(":checked")
All checked input elements

<script>
$(document).ready(function(){
  $("input").focus();
  $(":focus").css("background-color","yellow");
});
</script>

 

 JQuery Event Methods

Event methods trigger or attach a function to an event handler for the selected elements.
The following table lists all the jQuery methods used to handle events.
Method
Description
bind()
Attaches event handlers to elements
blur()
Attaches/Triggers the blur event
change()
Attaches/Triggers the change event
click()
Attaches/Triggers the click event
dblclick()
Attaches/Triggers the double click event
delegate()
Attaches a handler to current, or future, specified child elements of the matching elements
die()
Removed in version 1.9. Removes all event handlers added with the live() method
error()
Deprecated in version 1.8. Attaches/Triggers the error event
event.currentTarget
The current DOM element within the event bubbling phase
event.data
Contains the optional data passed to an event method when the current executing handler is bound
event.delegateTarget
Returns the element where the currently-called jQuery event handler was attached
event.isDefaultPrevented()
Returns whether event.preventDefault() was called for the event object
event.isImmediatePropagationStopped()
Returns whether event.stopImmediatePropagation() was called for the event object
event.isPropagationStopped()
Returns whether event.stopPropagation() was called for the event object
event.namespace
Returns the namespace specified when the event was triggered
event.pageX
Returns the mouse position relative to the left edge of the document
event.pageY
Returns the mouse position relative to the top edge of the document
event.preventDefault()
Prevents the default action of the event
event.relatedTarget
Returns which element being entered or exited on mouse movement.
event.result
Contains the last/previous value returned by an event handler triggered by the specified event
event.stopImmediatePropagation()
Prevents other event handlers from being called
event.stopPropagation()
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event
event.target
Returns which DOM element triggered the event
event.timeStamp
Returns the number of milliseconds since January 1, 1970, when the event is triggered
event.type
Returns which event type was triggered
event.which
Returns which keyboard key or mouse button was pressed for the event
focus()
Attaches/Triggers the focus event
focusin()
Attaches an event handler to the focusin event
focusout()
Attaches an event handler to the focusout event
hover()
Attaches two event handlers to the hover event
keydown()
Attaches/Triggers the keydown event
keypress()
Attaches/Triggers the keypress event
keyup()
Attaches/Triggers the keyup event
live()
Removed in version 1.9. Adds one or more event handlers to current, or future, selected elements
load()
Deprecated in version 1.8. Attaches an event handler to the load event
mousedown()
Attaches/Triggers the mousedown event
mouseenter()
Attaches/Triggers the mouseenter event
mouseleave()
Attaches/Triggers the mouseleave event
mousemove()
Attaches/Triggers the mousemove event
mouseout()
Attaches/Triggers the mouseout event
mouseover()
Attaches/Triggers the mouseover event
mouseup()
Attaches/Triggers the mouseup event
off()
Removes event handlers attached with the on() method
on()
Attaches event handlers to elements
one()
Adds one or more event handlers to selected elements. This handler can only be triggered once per element
$.proxy()
Takes an existing function and returns a new one with a particular context
ready()
Specifies a function to execute when the DOM is fully loaded
resize()
Attaches/Triggers the resize event
scroll()
Attaches/Triggers the scroll event
select()
Attaches/Triggers the select event
submit()
Attaches/Triggers the submit event
toggle()
Removed in version 1.9. Attaches two or more functions to toggle between for the click event
trigger()
Triggers all events bound to the selected elements
triggerHandler()
Triggers all functions bound to a specified event for the selected elements
unbind()
Removes an added event handler from selected elements
undelegate()
Removes an event handler to selected elements, now or in the future
unload()
Deprecated in version 1.8. Attaches an event handler to the unload event

Example:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("p").hover(function(){
    $("p").css("background-color","yellow");
    },function(){
    $("p").css("background-color","pink");
  });
});
</script>
</head>
<body>

<p>Hover the mouse pointer over this paragraph.</p>

</body>
</html>

 JQuery Effects


Jquery Fade
Jquery Hide/Show
Jquery Slide
Jquery Animate
Jquery stop()
Jqury callback
Jquery Chaining

JQuery HTML


Jquery Get
Jquery Set
Jquery Add
Jquery Remove
Jquery CSS classes
Jquery css()
Jquery Dimensions

 JQuery - AJAX Introduction

AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.
AJAX = Asynchronous JavaScript and XML.
In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.
Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.
You can learn more about AJAX in our AJAX tutorial.

What About jQuery and AJAX?

Query provides several methods for AJAX functionality.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Without jQuery, AJAX coding can be a bit tricky!

Writing regular AJAX code can be a bit tricky, because different browsers have different syntax for AJAX implementation. This means that you will have to write extra code to test for different browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code.

 JQuery - AJAX load() Method

 JQuery load() Method

The jQuery load() method is a simple, but powerful AJAX method.
The load() method loads data from a server and puts the returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);

The required URL parameter specifies the URL you wish to load.
The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
The optional callback parameter is the name of a function to be executed after the load() method is completed.
The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:
  • responseTxt - contains the resulting content if the call succeed
  • statusTxt - contains the status of the call
  • xhr - contains the XMLHttpRequest object
The following example displays an alert box after the load() method completes. If the load() method has succeed, it displays "External content loaded successfully!", and if it fails it displays an error message:
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
      if(statusTxt=="success")
        alert("External content loaded successfully!");
      if(statusTxt=="error")
        alert("Error: "+xhr.status+": "+xhr.statusText);
    });
  });      
});
</script>

 JQuery - AJAX get() and post() Methods

Two commonly used methods for a request-response between a client and server are: GET and POST.
  • GET - Requests data from a specified resource
  • POST - Submits data to be processed to a specified resource
GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

 JQuery $.get() Method

Syntax:
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("demo_test.asp",function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

 JQuery $.post() Method

The $.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>

 JQuery - The noConflict() Method

What if you wish to use other frameworks on your pages, while still using jQuery?
As you already know; jQuery uses the $ sign as a shortcut for jQuery.
What if other JavaScript frameworks also use the $ sign as a shortcut?
Some other popular JavaScript frameworks are: MooTools, Backbone, Sammy, Cappuccino, Knockout, JavaScript MVC, Google Web Toolkit, Google Closure, Ember, Batman, and Ext JS.
Some of the other frameworks also use the $ character as a shortcut (just like jQuery), and then you suddenly have two different frameworks using the same shortcut, which might result in that your scripts stop working.
The jQuery team have already thought about this, and implemented the noConflict() method.
The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
You can of course still use jQuery, simply by writing the full name instead of the shortcut
You can also create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in a  variable, for later use. Here is an example:
var jq = $.noConflict();
jq(document).ready(function(){
  jq("button").click(function(){
    jq("p").text("jQuery is still working!");
  });
});
è
If you have a block of jQuery code which uses the $ shortcut and you do not want to change it all, you can pass the $ sign in as a parameter to the ready method. This allows you to access jQuery using $, inside this function - outside of it, you will have to use "jQuery":
$.noConflict();
jQuery(document).ready(function($){
  $("button").click(function(){
    $("p").text("jQuery is still working!");
  });
});
Using load() method
Syntax:
$(selector).load(URL,data,callback);
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
      if(statusTxt=="success")
        alert("External content loaded successfully!");
      if(statusTxt=="error")
        alert("Error: "+xhr.status+": "+xhr.statusText);
    });
  });
});
Using $.ajax()
Syntax:-
$.ajax({name:value, name:value, ... })
The parameters specifies one or more name/value pairs for the AJAX request.
Possible names/values in the table below:
Name
 Value/Description
async
A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr)
A function to run before the request is sent
cache
A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status)
A function to run when the request is finished (after success and error functions)
contentType
The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
context
Specifies the "this" value for all AJAX related callback functions
data
Specifies data to be sent to the server
dataFilter(data,type)
A function used to handle the raw response data of the XMLHttpRequest
dataType
The data type expected of the server response.
error(xhr,status,error)
A function to run if the request fails.
global
A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified
A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp
A string overriding the callback function in a jsonp request
jsonpCallback
Specifies a name for the callback function in a jsonp request
password
Specifies a password to be used in an HTTP access authentication request.
processData
A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset
Specifies the charset for the request
success(result,status,xhr)
A function to be run when the request succeeds
timeout
The local timeout (in milliseconds) for the request
traditional
A Boolean value specifying whether or not to use the traditional style of param serialization
type
Specifies the type of request. (GET or POST)
url
Specifies the URL to send the request to. Default is the current page
username
Specifies a username to be used in an HTTP access authentication request
xhr
A function used for creating the XMLHttpRequest object

$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url:"demo_test.txt",success:function(result){
alert("External content loaded successfully!");
      $("#div1").html(result);
    }});
  });
});

 JQuery AJAX Methods

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
The following table lists all the jQuery AJAX methods:
Method
Description
$.ajax()
Performs an async AJAX request
$.ajaxPrefilter()
Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup()
Sets the default values for future AJAX requests
$.ajaxTransport()
Creates an object that handles the actual transmission of Ajax data
$.get()
Loads data from a server using an AJAX HTTP GET request
$.getJSON()
Loads JSON-encoded data from a server using a HTTP GET request
$.getScript()
Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param()
Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post()
Loads data from a server using an AJAX HTTP POST request
ajaxComplete()
Specifies a function to run when the AJAX request completes
ajaxError()
Specifies a function to run when the AJAX request completes with an error
ajaxSend()
Specifies a function to run before the AJAX request is sent
ajaxStart()
Specifies a function to run when the first AJAX request begins
ajaxStop()
Specifies a function to run when all AJAX requests have completed
ajaxSuccess()
Specifies a function to run when an AJAX request completes successfully
load()
Loads data from a server and puts the returned data into the selected element
serialize()
Encodes a set of form elements as a string for submission
serializeArray()
Encodes a set of form elements as an array of names and values



0 comments:

Post a Comment