الأربعاء، 11 مارس 2015

How to Create Animated Visual Effects Using jQuery

You can create animated visual effects by setting the CSS visibility property, i.e. making elements appearing and disappearing. Along with making an element appear and disappear, we might reduce the value of its opacity property over the certain period. This king of animated visual effect creates a more pleasing experience for user and jQuery makes them easy.

jQuery defines simple methods such as fadeIn() and fadeOut() for basic visual effects. You can also use an animate() method for producing more complex custom animations. 

Every animation has a duration that specifies how long the effect should last for. You can specify this as a number of milliseconds or by using a string. The string "fast" means 200ms and the sting "slow" means 600ms. If you specify a duration string that jQuery does not recognize, you will get a default duration of 400ms. 

$("#animation").fadeIn(); 
// It fades an element in over 400ms
$("#animation").fadeOut("fast");
// It fade outs over 200ms
$("#animation").fadeIn(5000);
//It fades an element in over 5000ms

You can also define new duration names by adding new string-to-number mappings to jQuery.fx.speeds as given below. 

jQuery.fx.speeds["medium-fast"]=3000;
jQuery.fx.speeds["medium-slow"]=5000;

Here is an example to create animated visual effects using methods fadeIn() and fadeOut() in jQuery 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
jQuery.fx.speeds["medium-slow"]=3000;
jQuery.fx.speeds["very-slow"]=5000;
$(document).ready(function(){
$("#btn1").click(function(){
$("#animation1").fadeIn();
$("#animation3").fadeIn(5000);
$("#animation5").fadeIn("medium-slow");
});
$("#btn2").click(function(){
$("#animation2").fadeOut("fast");
$("#animation4").fadeOut("very-slow");
});
});
</script>
<input type=button id="btn1" value="Start FadeIn"/><br/>
<div id="animation1" style="display:none;background:pink;">It fades an element in over 400ms</div><br/>
<div id="animation3" style="display:none;background:red">It fades an element in over 5000ms</div><br/>
<div id="animation5" style="display:none;background:yellow">It fades an element in over 3000ms</div><br/>

<input type=button id="btn2" value="Start FadeOut"/><br/>
<div id="animation2" style="background:red">It fade outs over 200ms</div><br/>
<div id="animation4" style="background:pink">It fade outs over 5000ms</div><br/>

Preview:







It fade outs over 200ms

It fade outs over 5000ms

You can also set the value of the document that was animated using a function as argument. Here is a jQuery code which quickly fade in an element and when it is visible, display some text in it. 

<script>
$(document).ready(function(){
$("#btn4").click(function(){
$("#message").fadeIn("fast", function() {$("#message").text("Hello this is animation");});
});});
</script>
<input type=button id="btn4" value="Start Animation"/><br/>
<div id="message" style="color:red"></div>

Preview:






Passing a callback function to an effect method allows you to perform actions at the end of an effect. However, that is is not necessary when you simply want to perform multiple effects in sequence. If you call an animation method on an element that is already being animated, the new animation does not begin right away but is deferred until the current animation ends. For example, you can make an element blink before fading in permanently. 

<script>
$(document).ready(function(){
$("#blinker").mouseover(function(){
$("#blinker").fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn();});
});
</script>
<div id="blinker" style="color:red"><h3>It blinks before fading in permanently</h3></div>

Preview:

It blinks before fading in permanently


jQuery's effect methods are declared to accept optional duration and callback arguments. It is also possible to invoke these methods with an object whose properties specify animation options. 

<script>
$(document).ready(function(){
$("#btn3").click(function(){
$("#effect").fadeIn({
duration: "slow",
complete: function(){$(this).text("Animation was completed");}
});});});
</script>
<input type=button id="btn3" value="Start Animation"/>
<div id="effect" style="background:yellow">This is sample animation effect</div>

Preview:



This is sample animation effect


Related Posts:

الخميس، 5 مارس 2015

How to Alter HTML Document Structure using jQuery?

HTML documents are represented as a tree of nodes rather than a linear sequence of characters, insertions, deletions, and replacements are not as simple as they are for strings and arrays. In jQuery there are some methods for making more complex changes to a document.

There are number of method in jQuery for inserting and replacing elements, copying elements, wrapping elements and deleting elements. For insertion and replacement of elements in HTML document, you can use the methods append(), prepend() and replacewith(). 

You can copy HTML elements using clone() method and wrapp the elements using wrap(), wrapInner() and wrapAll() methods. For deletion of the element you can use empty(), reomve() and unwrap() methods. 

How to Insert and Replace Elements using jQuery 


You can use different methods to insert and replace elements using jQuery, each of the methods takes an argument that specifies the content that is to be inserted into the document. 

The inserting can be made into or before or after or in place of each selected elements. If the content to be inserted is an element that already exists in the document, it is moved from current location.
The append() method inserts an element at the end of selected element, prepend() method inserts an element at start of selected element and replaceWith() method replaces one selected element with another. For append(), prepend() and replacewith() the second argument is the current content of the element as an HTML string. 

There are before() and after() methods, which can be used to insert before and after of each selected elements. For before() and after() the function is invoked with no second argument. 

Here are some examples of jQuery codes for inserting and replacing elements using jQuery. 

$("#clr").append("<br/>"+message); 
// It adds a content at end of the #clr element

$("h1").prepend(":"); 
// It adds colon sign at the star of each <h1>

$("h1").before("<hr/>");
// It insert horizontal line before each <h1> element

$("h1").after("<hr/>");
// It insert horizontal line after each <h1> element

$("hr").replaceWidth("<br/>");
// It replaces <hr/> elements with <br/>

$("h2").each(function(){
var h2=$(this);
h2.replaceWith("<h1>"+h2.html()+"</h1>");
});
// It replaces <h2> with <h1> keeping the content.

Similary, you can use appendTo(), prependTo(), insertAfter(), insertBefore and replaceAll() methods for the same purpose as given in the example below. 

$("<br/>"+message).appendTo("#clr"); 
// It adds a content at end of the #clr element
$(document.createTextNode(":")).prependTo("h1");
// It adds colon sign at the star of each <h1>
$("<hr/>").insertBefore("h1");
// It insert horizontal line before each <h1> element
$("<hr/>").insertAfter("h1");
// It insert horizontal line after each <h1> element
$("<br/>").replaceAll("hr");
// It replaces <hr/> elements with <br/>

How to Copy Elements using jQuery 


If you insert elements that are already part of the document, those elements will simply be moved, not copied to their new location. 

If you want to copy elements to a new location instead of moving them, you must first make a copy with the clone() method. clone() makes and returns a copy of each selected element and all the descendent's of those elements. 

An example for copying elements using clone() method is given below. 

$(document.body).append("<div id="linklist"><h1>List of Links</h1></div>");
//It appends a new div with id "linklist", to the end of the document
$("a").clone().appendTo("#linklist");
//It copy all links in the document and insert them into that new div
$("#linklist>a").after("<br/>");
//It insert <br/> elements after each link so they display on separate lines

How to Wrap Elements using jQuery 


Another type of insertion into an HTML document involves wrapping a new element or elements around one or more elements. jQuery defines three wrapping functions, wrap() wraps each of the selected elements, wrapInner() wraps the contents of each selected element and wrapAll() wraps the selected elements as a group. 

$("h1").wrap(document.createElement("i"));
//It produces <i><h1> .....</h1></i>

$("h1").wrapInner("<i/>");
//It produces <h1><i>........</i></h1>

$("body>p:first").wrap("<a name="lead"><div class="first"></div></a>");
// It wraps the first paragraph in one anchor and div

$("body>p:not(:first)").wrapAll("<div class="rest"></div>");
//It wraps all the other paragraps in another div

How to Delete Elements using jQuery 


Along with insertions and replacements, jQuery also defines methods for deleting elements. empty() removes all children including text nodes or each of the selected elements, without altering the elements themselves. The remove() method, by contrast removes the selected elements and all their content from the document. remove() is normally invoked with no arguments and removes all elements in the jQuery object. 

 $("#hide").empty();
// It removes all the contents having id #hide

$("#rmv").remove(); 
// It removes the contents and events having id #rmv

You can use unwrap() method to perform element removal in a way that is the opposite of the wrap() or wrapAll() method. It removes the parent element of each selected element without affecting the selected elements or their siblings. 


Related Posts:

الاثنين، 2 مارس 2015

How to Get and Set Element Attributes using jQuery

Some of the simplest and most common, operations on jQuery objects are those that get or set the value of HTML attributes, CSS styles, element content, or element geometry. In this post I am going to describe the methods to get or set HTML element attributes using jQuery.

How to Get and Set HTML Attributes using jQuery


You can get or set HTML attributes using attr() method in jQuery. The attr() method handles browser incompatibilities and special cases and allows you to use either HTML attributes names or their JavaScript property equivalents.

Here are some examples of uses of attr() method for getting or setting HTML attributes.

$("form").attr("action");  
// It gets the action attribute from the first form.

$("#icon").attr("src", "icon.gif");  
// It sets the src attributes for image with id icon.

$("a").attr("target", "_blank");  
// It set the target attributes for all links to load in new windows

$("a").attr("target", function(){
if(this.host==location.host) return "_self"
else return "_blank";
});

This function sets the attribute of all external links load in new windows and internal links load in the same window.

There is another method related to attr() is removeAttr(), which is related function that completely removes an attributes from all selected elements.

Here an example of uses of removeAttr() method for removing HTML attributes.

$("a").removeAttr("target");

It removes the target attribute of link and makes all links load in the same window.

How to Get and Set CSS Attributes using jQuery


The css() method is very much like attr() method, but is works with the CSS styles of an element rather than the HTML attributes of the element.

When querying style values, css() returns the current style of the element and the returned value may come from the style attribute or from a style-sheet.

Here are some examples getting and setting CSS attributes using attr() method.

$("h1").css("font-weight"); 
// It gets font weight of first <h1>

$("h1").css("font-variant", "smallcaps"); 
// It sets font-variant property of <h1> to smallcaps.

$("h1").css({backgroundColor:"black",textColor:"white",
fontVariant:"small-caps", padding: "10px 2px 4px 20px",
border:"dotted black 4px"});
// It sets multiple styles at once for <h1>

How to Get and Set CSS Classes using jQuery


jQuery defines convenience methods for working with the class attribute. addClass() and removeClass() add and remove classes from the selected elements. toogleClass() adds classes to elements that don't already have them and removes classes from those that do. hasClass() tests for the presence of a specified class.

Here are are some examples for adding css classes, removing css classes, toggling css classes and testing css classes.

Adding CSS Classes

$("h1").addClass("hilite");  
// It adds a class to all <h1> elements

$("h1+p").addClass("hilite first"); 
// It adds two classes to elements after <h1>

$("section").addClass(function(n){return "scetion"+n;}); 
// It passes a function to add a custom class to each matched element

Removing CSS classes

$("p").removeClass("hilite");  
// It removes a class from all p elements

$("p").removeClass("hilite first"); 
// It removes two classes from <p> elements

$("section").removeClass(function(n){return "scetion"+n;}); 
// It passes a function to remove a custom class to each matched element

Toggling CSS Classes

$("tr:odd").toggleClass("oddrow"); 
// It adds the class if it is not there or remove if it is.

$("h1").toggleClass("big bold");   
// It toggles two classes at once.

$("h1").toggleClass(function(n){
return "big bold h1-" +n; });
// It toggles a computed class or classes.

$("h1").toggleClass("hilite", true); 
// It works like addclass

$("h1").toggleClass("hilite", false); 
// It works like removeclass

Testing CSS Classes

$("p").hasClass("first")  
// It tests any p element have class first

$("#lead").is("first") 
// It test any element with id lead have class first

The hasClass() method is less flexible than addclass(), removeClass, and toggleClass(). hasClass() works for only a single class name and does not support function arguments. It returns true if any of the selected elements has the specified CSS class and returns false if none of them do. The is() method is more flexible and can be used for the same purpose.

How to Get and Set HTML Form Values Using jQuery


For setting and querying the value attribute of HTML form elements val() method is used and it is also used for querying and setting the selection state of check-boxes, radio buttons, and select elements. Here are some examples of getting and setting HTML form values using val() method. 

$("#firstname").val()  
// It gets value from the firstname text field.

$("select #extras").val() 
// It gets array of values from <select multiple< from element.

$("input:radio[name=ship]:checked").val() 
// It gets value of checked radio button.

How to Get and Set Element Content Using jQuery


The text() and html() methods query and set the plain-text or HTML content of an element or elements. When invoked with no arguments, text() returns the plain text content of all descendant text nodes of all matched elements. This works even in browsers that do not support the textContent or innerText properties. Here are some examples of getting and setting element content using text() and html() method 

var title=$("head title").text() //It gets document title
var headline=$("h1").html()
//It gets the html of first <h1> element

$("h1").text(function(n,current){
return "$" + (n+1) + ": "+current });
// It gives section number for each headings

How to Get and Set Element Geometry Using jQuery


To query or set the position of an element, use the offset() method. This method measures positions relative to the document and returns them in the form of an object with left and top properties that hold the X and Y coordinates. It you pass an object with these properties to the method, it sets the position you specify. Here are some examples of getting and setting element geometry using offset() method 

var elt=$("#sprite");
var position=elt.offset();
// It gets the current position of an elememt
position.top +=100;
// It changes its Y coordinate 100px.
elt.offset(position);

How to Get and Set Element Data Using jQuery


jQuery defines a getter or setter method named data() that sets or queries data associated with any document element or with the Document or window objects. You can also use removeData() method to remove data from an element or elements. Here are some examples of getting and setting element data using data() method removing data using removeData() method. 

$("div").data("x",1); 
//It sets some data "x" to div
$("div.nodata").removeData("x");
//It removes some data "x" from div with class nodata
var x=$("#mydiv").data("x");
//It query some data from element id "mydiv"


Related Posts:

الأحد، 1 مارس 2015

How to Use jQuery With HTML?

jQuery() is a single global function defined by jQuery library. This function is so frequently used that the library also defines the global symbol $ as a shortcut for it.

This single global function with two names is the central query function for jQuery. For example, if you need to ask for the set of all <div> elements in a document, write the following code.

var divs=$("div");

The value returned by the jQuery() function represents a set of zero or more DOM elements is known as a jQuery object. jQuery objects define many methods for operating on the sets of elements they represent.

How to Obtain jQuery


jQuery library is free software. You can download if from http://www.jquery.com. Once you have download the code, you can include it in your web pages with a <script> element as given below.
<script src="jquery-1.11.2.min.js"></script>

Here the "min" in the filename indicates that this is the minimized version of the library, with unnecessary comments and whitespace removed, and internal identifiers replaced with shorter ones.

And another way to use jQuery in your web application is to allow a Content Distribution Network (CDN) to serve it using a URL like one of these. 

Google CDN


https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js

Microsoft CDN


http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js

jQuery CDN


http://code.jquery.com/jquery-2.1.3.min.js
http://code.jquery.com/jquery-1.11.2.min.js


If you use Google CDN, you can use "1.11" to get the latest release in the 1.11.x series, or just "1" to get the most current release less than 2.0.

The major advantage of loading jQuery from well-known URLs like these is that, because of jQuery's popularity, visitors to your website will likely already have a copy of the library in the browser's cache and no download will be necessary.

How to Use jQuery() Function


The jQuery() function is the most important one in the jQuery library. It is heavily overloaded, however, and there are four different ways you can invoke it.

The first, and the most common way to invoke $() is to pass a CSS selector to it. Which returns the set of elements from the current document that match the selector as given in the example below.

var id=$("#id");
var class=$(".class");

And the another way to invoke $() is to pass it an Element or Document or Window object. It simply wraps the element, document or window in a jQuery object and returns that object. Doing this allows you to use jQuery methods to manipulate the element rather than using raw DOM methods. For example you can call $(document) or $(this) to pass document or current element.

The third way to invoke $() is to pass it a string of HTML text. When you do this, jQuery creates the HTML element or elements described by that text and then returns a jQuery object representing those elements.

When invoked in this way, $() accepts an optional second argument. You can pass a document object to specify the document with which the elements are to be associated. If you do this, the object properties are assumed to specify the names and values of HTML attributes to be set on the object.

Here is an example, where three arguments are used to set the url, css of the image and the click event on the image.

var img=$("<img />"),
{src:url,
css:{borderWidth:5},
click:handleClick
});

And the fourth way to invoke $() is to pass a function to it. If you do this, the function you pass will be invoked when the document has been loaded and the DOM is ready to be manipulated. For example here is a jQuery version of onLoad() function which is invoked when the document has loaded.

$(function(){
// jQuery code
});

Read Next:How to Get and Set Element Attributes using jQuery

Related Search Terms

Related Posts: