Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Thursday, 28 April 2011

jQuery and Ajax


jQuery has a rich library of methods (functions) for AJAX development.

jQuery AJAX Example

Let AJAX change this text

AJAX is not a programming language.
It is just a technique for creating better and more interactive web applications.


The example above is taken from our AJAX tutorial, but modified with jQuery syntax. 

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
You can learn more about AJAX in our AJAX tutorial.

AJAX and jQuery

jQuery provides a rich set of methods for AJAX web development.
With jQuery AJAX, you can request TXT, HTML, XML or JSON data from a remote server using both HTTP Get and HTTP Post.
And you can load remote data directly into selected HTML elements of your web page!

Write Less, Do More

The jQuery load() method is a simple (but very powerful) AJAX function. It has the following syntax:
$(selector).load(url,data,callback)

Use the selector to define the HTML element(s) to change, and the url parameter to specify a web address for your data.

Only if you want to send data to the server, you need to use the data parameter. Only if you need to trigger a function after completion, you will use the callback parameter.

Low Level AJAX

$.ajax(options) is the syntax of the low level AJAX function.
$.ajax offers more functionality than higher level functions like load, get, and post, but it is also more difficult to use.

The option parameter takes name|value pairs defining url data, passwords, data types, filters, character sets, timeout and error functions.


jQuery AJAX Methods From This Page:

RequestDescription
$(selector).load(url,data,callback)Load remote data into selected elements
$.ajax(options)Load remote data into an XMLHttpRequest object

jQuery and CSS


jQuery css() Method

jQuery has one important method for CSS manipulation: css()
The css() method has three different syntaxes, to perform different tasks.
  • css(name) - Return CSS property value
  • css(name,value) - Set CSS property and value
  • css({properties}) - Set multiple CSS properties and values

Return CSS Property

Use css(name) to return the specified CSS property value of the FIRST matched element:

Example

$(this).css("background-color");


Set CSS Property and Value

Use css(name,value) to set the specified CSS property for ALL matched elements:

Example

$("p").css("background-color","yellow");


Set Multiple CSS Property/Value Pairs

Use css({properties}) to set one or more CSS property/value pairs for the selected elements:

Example

$("p").css({"background-color":"yellow","font-size":"200%"});


jQuery height() and width() Methods

jQuery has two important methods for size manipulation.
  • height()
  • width()

Size Manipulation Examples

The height() method sets the height of all matching elements:

Example

$("#div1").height("200px");
The width() method sets the width of all matching elements:

Example

$("#div2").width("300px");


jQuery CSS Methods From this Page:

CSS PropertiesDescription
$(selector).css(name)Get the style property value of the first matched element
$(selector).css(name,value)Set the value of one style property for matched elements
$(selector).css({properties})Set multiple style properties for matched elements
$(selector).height(value)Set the height of matched elements
$(selector).width(value)Set the width of matched elements

jQuery HTML Manipulation


jQuery contains powerful methods (functions) for changing and manipulating HTML elements and attributes.

Changing HTML Content

$(selector).html(content)

The html() method changes the contents (innerHTML) of matching HTML elements.

Example

$("p").html("W3Schools");


Adding HTML content

$(selector).append(content)
The append() method appends content to the inside of matching HTML elements.
$(selector).prepend(content)
The prepend() method "prepends" content to the inside of  matching HTML elements.

Example

$("p").append(" W3Schools");
$(selector).after(content)
The after() method inserts HTML content after all matching elements.
$(selector).before(content)
The before() method inserts HTML content before all matching elements.

Example

$("p").after(" W3Schools.");


jQuery HTML Manipulation Methods From This Page:

FunctionDescription
$(selector).html(content)Changes the (inner) HTML of selected elements
$(selector).append(content)Appends content to the (inner) HTML of selected elements
$(selector).after(content)Adds HTML after selected elements

jQuery Callback Function


A callback function is executed after the current animation is 100% finished.

jQuery Callback Functions

A callback function is executed after the current animation (effect) is finished.
JavaScript statements are executed line by line. However, with animations, the next line of code can be run even though the animation is not finished. This can create errors.
To prevent this, you can create a callback function. The callback function will not be called until after the animation is finished.

jQuery Callback Example

Typical syntax: $(selector).hide(speed,callback)
The callback parameter is a function to be executed after the hide effect is completed:

Example with Callback

$("p").hide(1000,function(){
  alert("The paragraph is now hidden");
});
Without a callback parameter, the alert box is displayed before the hide effect is completed:

Example without Callback

$("p").hide(1000);
alert("The paragraph is now hidden");

jQuery Effects


Examples

jQuery hide()
Demonstrates a simple jQuery hide() method.
jQuery hide()
Another hide() demonstration. How to hide parts of text.
jQuery slideToggle()
Demonstrates a simple slide panel effect.
jQuery fadeTo()
Demonstrates a simple jQuery fadeTo() method.
jQuery animate()
Demonstrates a simple jQuery animate() method.

jQuery Hide and Show

With jQuery, you can hide and show HTML elements with the hide() and show() methods:

Example

$("#hide").click(function(){
  $("p").hide();
});
$("#show").click(function(){
  $("p").show();
});
Both hide() and show() can take the two optional parameters: speed and callback.
Syntax:
$(selector).hide(speed,callback)
$(selector).show(speed,callback)
The speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", "normal", or milliseconds:

Example

$("button").click(function(){
  $("p").hide(1000);
});
The callback parameter is the name of a function to be executed after the hide (or show) function completes. You will learn more about the callback parameter in the next chapter of this tutorial.

jQuery Toggle

The jQuery toggle() method toggles the visibility of HTML elements using the show() or hide() methods.
Shown elements are hidden and hidden elements are shown.
Syntax:
$(selector).toggle(speed,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.

Example

$("button").click(function(){
  $("p").toggle();
});
The callback parameter is the name of a function to be executed after the hide (or show) method completes.

jQuery Slide - slideDown, slideUp, slideToggle

The jQuery slide methods gradually change the height for selected elements.
jQuery has the following slide methods:
$(selector).slideDown(speed,callback)
$(selector).slideUp(speed,callback)
$(selector).slideToggle(speed,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
The callback parameter is the name of a function to be executed after the function completes.

slideDown() Example

$(".flip").click(function(){
  $(".panel").slideDown();
});

slideUp() Example

$(".flip").click(function(){
  $(".panel").slideUp()
})

slideToggle() Example

$(".flip").click(function(){
  $(".panel").slideToggle();
});


jQuery Fade - fadeIn, fadeOut, fadeTo

The jQuery fade methods gradually change the opacity for selected elements.
jQuery has the following fade methods:
$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
The speed parameter can take the following values: "slow", "fast", "normal", or milliseconds.
The opacity parameter in the fadeTo() method allows fading to a given opacity.
The callback parameter is the name of a function to be executed after the function completes.

fadeTo() Example

$("button").click(function(){
  $("div").fadeTo("slow",0.25);
});

fadeOut() Example

$("button").click(function(){
  $("div").fadeOut(4000);
});


jQuery Custom Animations

The syntax of jQuery's method for making custom animations is:
$(selector).animate({params},[duration],[easing],[callback])
The key parameter is params. It defines the CSS properties that will be animated. Many properties can be animated at the same time:
animate({width:"70%",opacity:0.4,marginLeft:"0.6in",fontSize:"3em"});
The second parameter is duration. It specifies the speed of the animation. Possible values are "fast", "slow", "normal", or milliseconds.

Example 1

<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({height:300},"slow");
    $("div").animate({width:300},"slow");
    $("div").animate({height:100},"slow");
    $("div").animate({width:100},"slow");
  });
});
</script> 

Example 2

<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({left:"100px"},"slow");
    $("div").animate({fontSize:"3em"},"slow");
  });
});
</script> 

lampHTML elements are positioned static by default and cannot be moved.
To make elements moveable, set the CSS position property to fixed, relative or absolute.


jQuery Effects

Here are some examples of effect functions in jQuery: 
FunctionDescription
$(selector).hide()Hide selected elements
$(selector).show()Show selected elements
$(selector).toggle()Toggle (between hide and show) selected elements
$(selector).slideDown()Slide-down (show) selected elements
$(selector).slideUp()Slide-up (hide) selected elements
$(selector).slideToggle()Toggle slide-up and slide-down of selected elements
$(selector).fadeIn()Fade in selected elements
$(selector).fadeOut()Fade out selected elements
$(selector).fadeTo()Fade out selected elements to a given opacity
$(selector).animate()Run a custom animation on selected elements

jQuery Events


jQuery is tailor made to handle events.

jQuery Event Functions

The jQuery event handling methods are core functions in jQuery.
Event handlers are method that are called when "something happens" in HTML. The term "triggered (or "fired") by an event" is often used. 
It is common to put jQuery code into event handler methods in the <head> section:

Example

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(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>
</html>
In the example above, a function is called when the click event for the button is triggered:
$("button").click(function() {..some code... } )
The method hides all <p> elements:
$("p").hide();

Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, put your jQuery functions in a separate .js file.
When we demonstrate jQuery here, the functions are added directly into the <head> section, However, sometimes it is preferable to place them in a separate file, like this (refer to the file with the src attribute):

Example

<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="my_jquery_functions.js"></script>
</head>


jQuery Name Conflicts

jQuery uses the $ sign as a shortcut for jQuery.
Some other JavaScript libraries also use the dollar sign for their functions.
The jQuery noConflict() method specifies a custom name (like jq), instead of using the dollar sign.


jQuery Events

Here are some examples of event methods in jQuery: 
Event MethodDescription
$(document).ready(function)  Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function)Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function)Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function)Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function)Triggers, or binds a function to the mouseover event of selected elements