Tuesday 29 November 2011

Facebook Style Alert Confirm Box with jQuery and CSS

                 

Create a facebook style alert box with jquery plug-in jquery.alert.js. Bellow is the complete tutorial

HTML / Javascript Code
Contains javascript and HTML Code.



<link href="facebook.alert.css" rel="stylesheet" type="text/css">

<script type="text/javascript"

src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>

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

<script type="text/javascript"> $(document).ready( function()

{ $("#delete_confirm").click( function()

{ jConfirm('Are you sure you want ot delete this thread?', '', function(r)

{ if(r==true) { $("#box").fadeOut(300); } }); }); });

</script>
<div id="box" style=" background-color:#ffffcc;">

<a href="#" id="delete_confirm">Delete</a>

</div>



facebook.alert.css
Contains CSS code.



#popup_container

{

font-family:'Lucida Grande',arial;

font-weight:bold;

text-align:left;

font-size: 12px;

width: 364px;

height: 86px;

background: #F3F3F3;

border:solid 1px #dedede;

border-bottom: solid 2px #456FA5;

color: #000000; }
#popup_title

{ display:none; }
#popup_message

{ padding-top: 15px; padding-left: 15px; }
#popup_panel

{ text-align: left; padding-left:15px; }
input

{

background-color:#476EA7;

padding:3px; color:#FFFFFF;

margin-top:20px;

margin-right:10px;

}


Hack an Website ? SQL Injection ? Very simple

Are you looking for some useful tips to improve your web projects security? In this post I suggest you some interesting points about this topic.

Hacking is very interesting topic you can improve programming skill.

SQL Injection

SQL Injection like this

Login Java Code
String userid = request.getParameter("userid");
String password = request.getParameter("password");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:projectDB");query = "SELECT * FROM Users WHERE user_id ='" + userid + "' AND password ='" + password +"'";

PreparedStatement ps = connection.prepareStatement(query);
ResultSet users = ps.executeQuery();

if(users.next()){

//some thing here
}
else{

}


Injection Works like this
query = "SELECT * FROM Users WHERE user_id ='' OR 1=1; /* AND password ='*/--'";

Login PHP Code;
Username = ' OR 1=1;//
Password = ....
$myusername=$_POST['usr'];
$mypassword=$_POST['pwd'];$sql="SELECT * FROM users WHERE user='$myusername' and password='$mypassword'";

$result=mysql_query($sql);
$count=mysql_num_rows($result);

if($count==1){

//some code
}
else {

}


Injection Works like this
$sql="SELECT * FROM users WHERE user=''OR 1 = 1;//' and password='....'";

How to avoid these mistakes Use addSlashes() function adding slashes(/) to the string in java and php
//Java Code
addSlashes(String userid);// PHP Code
$myusername=addslashes($_POST['usr'];);


Hacker is intelligent than programmer. So always hide the file extension (eg: *.jsp,*.php,*.asp).

http://xyz.com/login.php to http://xyz.com/login
http://xyz.com/login to http://xyz.com/signin.do
In Java redirect this URL links using Web.xml file and inn php write .htaccess file in root directory.

My Best Hacking Training Site Hackthissite.org

Hacker's Game full control with Unix based commands. Play and learn many more hacking things

http://itswadesh.wordpress.com/2011/11/29/prepared-statements-in-php-and-mysqli/

Prepared Statements in PHP and MySQLi

This article is intended for readers who have experience using PHP and MySQL. You should also have a general understanding of databases and programming (both procedural and object-oriented) as well as how to use PHP to execute a simple query to MySQL. I will not cover how to install PHP or MySQL, however at the end of the article are some links to help you get started with the installation process and for some further reading on the subject. I will be covering the basics of prepared statements in PHP and MySQLi and why you should consider using them in your own code as well as some technical explanation as to why you should use them.

Introduction

If you are like me and most other people, you probably have not taken the time to learn about web security when you first started writing server-side code. This is very dangerous as most people never even go back and try to make their code secure (or they simply forget). Writing their code in the same way that they originally learned how to can cause some serious vulnerabilities in the code, allowing hacking techniques such as SQL Injections to be fairly easy. If you have no idea what MySQL injections or cross side scripting is, then you should do some research, for example just go to Google and type in "SQL Injections" and there will be plenty of reading for you. I also would recommend a book called, "How to Break Web Software", it is a fantastic book that one of my professors told one of my classes about. It can teach you a lot about security, it is highly recommended. I will have an article written shortly on SQL Injections, so check back soon! If you do know what some of these nasty hacking techniques are then you are probably wondering why you should want to use prepared statements. There are basically three reasons why you should seriously consider writing prepared statements to execute your queries.

1. Prepared statements are more secure.
2. Prepared statements have better performance.
3. Prepared statements are more convenient to write.

Now that we know why prepared statements are better, let’s build an example so you can see for yourself. We’ll build a simple login example using prepared statements. First, I’ll show you the way most people would write it, then I’ll show you the way you could do it with a prepared statement which will be more secure, have better performance and be more convenient to write. Let’s get started!

The Well-known Way

If you are reading this article, chances are you already know how to execute a simple MySQL query in PHP. For those of you who do not know how to do this, it would look similar to this:

/* Connect to the Database */

$dbLink = mysql_connect("localhost", "username", "password");

if (!dbLink) {
echo 'db link fail';
}

/* Select the database */
mysql_select_db("databaseName");

/* Query and get the results */
$query = "SELECT * FROM testUsers WHERE username='$user' AND
password='$pass'";
$result = mysql_query($query);

/* Loop through the results */
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Username: " . $row["username";
}


What is the problem with this code? Simple, someone could use a simple SQL injection to get around the password authentication. Why is this code angerous? If you know what an SQL injection does, it basically bypasses the password condition by commenting it out and uses an always true statement which allows access. Building strings on the fly like this should make you very nervous, but how do we make it more secure? Say hello to prepared statements.

Prepared Statements

What is so great about prepared statements and why are they more secure? The simple answer is because prepared statements can help increase security by separating the SQL logic from the data being supplied. In the previous example we saw how the data is basically built into the SQL logic by building the query as a string on the fly. Let’s take a look at what a prepared statement can look like.

/* Create a new mysqli object with database connection parameters */

$mysqli = new mysql('localhost', 'username', 'password', 'db');

if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */

if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters

s - string, b - boolean, i - int, etc */

$stmt -> bind_param("ss", $user, $pass);

/* Execute it */
$stmt -> execute();
/* Bind results */

$stmt -> bind_results($result);
/* Fetch the value */

$stmt -> fetch();

echo $user . "'s level of priviledges is " . $result;
/* Close statement */

$stmt -> close();
}
/* Close connection */

$mysqli -> close();


Doesn’t look too bad, right? In short, the above code basically creates a new mysqli object and connects to the database. We then create a prepared statement and bind the incoming parameters to that statement, execute it and get the result. We then close the statement and connect and we’re done! Pretty easy!

Let’s take a look at where the security happens in these few lines:
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
$stmt -> bind_param("ss", $user, $pass);

Instead of grabbing and building the query string using things like $_GET['username'], we have ?'s instead. These ?'s separate the SQL logic from the data. The ?'s are place holders until the next line where we bind our parameters to be the username and password. The rest of the code is pretty much just calling methods which you can read about by following some of the links at the end of the article.

I hope this was helpful to you and if you have any questions feel free to post some comments below!

Saturday 26 November 2011

Old Standalone Softwares link

These days most of  the products are moving into its lite version. Sometimes i need a standalone copy of it to be saved into my computer so that every time i install windows XP i need not have to download those again.

So i collected links of essential softwares. And here are those.

Adobe Acrobat Reader Version 8

Google Chrome Standalone

Skype Standalone Offline Installer

Download AVG Antivirus 2012 32-bit (137 MB)

You are always welcome to add more links helping your friends find all of them at one place.

Facebook Style Footer Admin Panel

                 

The popularity of social media has been booming in the past few years and Facebook definitely has climbed high to the top of the social network rankings. Facebook has many Ajax driven features and applications that are very impressive, and one of the things I particularly like is the footer admin panel, where it neatly organizes frequently used links and applications.

This week I would like to cover part 1 of how to recreate the Facebook footer admin panel with CSS and jQuery.


Step 1. Wireframe and Tooltip Bubbles – HTML & CSS


Lay out the wireframe of the admin panel using an unordered list for the foundation. The last two list items (Alert Panel & Chat Panel) will have sub-panels nested within them. Since these two panels will float to the right, the order in the markup will be reversed.

Tooltip foundation

Notice that there is a <small> tag nested within the <a> tag, this is how we will achieve our tooltip bubble on the navigation.

HTML


<div id="footpanel">
<ul id="mainpanel">
<li><a href="#">Inspiration <small>
Design Bombs</small></a></li>
<li><a href="#">View Profile <small>
View Profile</small></a></li>
<li><a href="#">Edit Profile <small>
Edit Profile</small></a></li>
<li><a href="#">Contacts <small>
Contacts</small></a></li>
<li><a href="#">Messages (10) <small>
Messages</small></a></li>
<li><a href="#">Play List <small>
Play List</small></a></li>
<li><a href="#">Videos <small>
Videos</small></a></li>
<li id="alertpanel"><a href="#">
Alerts</a></li>
<li id="chatpanel"><a href="#">
Friends (<strong>18</strong>)</a></li>
</ul>
</div>

CSS


First start by fixing the panel to the bottom of the viewport.
#footpanel {
position: fixed;
bottom: 0; left: 0;
z-index: 9999;
/*--Keeps the panel on top of all other elements--*/
background: #e3e2e2;
border: 1px solid #c3c3c3;
border-bottom: none;
width: 94%;
margin: 0 3%;
}

As you may already know, IE6 does not understand fixed positioning. I stumbled across a tutorial that fixed this problem*.
*html #footpanel { /*--IE6 Hack - Fixed Positioning to the Bottom--*/
margin-top: -1px;
/*--Prevents IE6 from having an infinity scroll bar - due to 1px border on #footpanel--*/
position: absolute;
top:expression(eval(
document.compatMode &&document.compatMode=='CSS1Compat')
?documentElement.scrollTop+(
documentElement.clientHeight-this.clientHeight)
: document.body.scrollTop +(
document.body.clientHeight-this.clientHeight));
}

*Note: Due to heavy loading on the browser, an alternative solution would be to either use an position: absolute; or if the situation/client allows it use display: none; for those with IE6.

Style the unordered list which will be the foundation of this panel.
#footpanel ul {
padding: 0; margin: 0;
float: left;
width: 100%;
list-style: none;
border-top: 1px solid #fff;
/*--Gives the bevel feel on the panel--*/
font-size: 1.1em;
}
#footpanel ul li{
padding: 0; margin: 0;
float: left;
position: relative;
}
#footpanel ul li a{
padding: 5px;
float: left;
text-indent: -9999px;
/*--For text replacement - Shove text off of the page--*/
height: 16px; width: 16px;
text-decoration: none;
color: #333;
position: relative;
}
html #footpanel ul li a:hover{ background-color: #fff; }
html #footpanel ul li a.active {
/*--Active state when sub-panel is open--*/
background-color: #fff;
height: 17px;
margin-top: -2px;
/*--Push it up 2px to attach the active button to sub-panel--*/
border: 1px solid #555;
border-top: none;
z-index: 200;
/*--Keeps the active link on top of the sub-panel--*/
position: relative;
}

Tooltip Demo

Declare the text replacement for each link.
You can download these great icons by Pinvoke here.
#footpanel a.home{
background: url(home.png) no-repeat 15px center;
width: 50px;
padding-left: 40px;
border-right: 1px solid #bbb;
text-indent: 0;
/*--Reset text indent since there will be a
combination of both text and image--*/
}
a.profile{ background: url(user.png)
no-repeat center center; }
a.editprofile{ background: url(wrench_screwdriver.png)
no-repeat center center; }
a.contacts{ background: url(address_book.png)
no-repeat center center; }
a.messages{ background: url(mail.png)
no-repeat center center; }
a.playlist{ background: url(document_music_playlist.png)
no-repeat center center; }
a.videos{ background: url(film.png)
no-repeat center center; }
a.alerts{ background: url(newspaper.png)
no-repeat center center; }
#footpanel a.chat{
background: url(balloon.png)
no-repeat 15px center;
width: 126px;
border-left: 1px solid #bbb;
border-right: 1px solid #bbb;
padding-left: 40px;
text-indent: 0;
/*--Reset text indent since there will be
a combination of both text and image--*/
}
#footpanel li#chatpanel, #footpanel li#alertpanel {
 float: right; }
/*--Right align the chat and alert panels--*/

Tooltip Demo

Style the tooltip bubble, by default the <small> tag will be hidden with a display:none;. On hover over, allow the tooltip to appear with a display:block;
#footpanel a small {
text-align: center;
width: 70px;
background: url(pop_arrow.gif) no-repeat center bottom;
padding: 5px 5px 11px;
display: none; /*--Hide by default--*/
color: #fff;
font-size: 1em;
text-indent: 0;
}
#footpanel a:hover small{
display: block; /*--Show on hover--*/
position: absolute;
top: -35px;
/*--Position tooltip 35px above the list item--*/
left: 50%;
margin-left: -40px; /*--Center the tooltip--*/
z-index: 9999;
}

Friday 25 November 2011

What is jQuery?

Since you've come to this page, you may already have a pretty good idea about what jQuery is, but to be on the safe side, here is a brief explanation. jQuery is a JavaScript framework, which purpose is to make it much easier to use JavaScript on your website. You could also describe jQuery as an abstraction layer, since it takes a lot of the functionality that you would have to write many lines of JavaScript to accomplish and wraps it into functions that you can call with a single line of code. It's important to note that jQuery does not replace JavaScript, and while it does offer some syntactical shortcuts, the code you write when you use jQuery is still JavaScript code. With that in mind, you should be aware that you don't need to be a JavaScript expert to use jQuery. In fact, jQuery tries to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation, so that you may do these things without knowing a lot about JavaScript. There are a bunch of other JavaScript frameworks out there, but as of right now, jQuery seems to be the most popular and also the most extendable, proved by the fact that you can find jQuery plugins for almost any task out there. The power, the wide range of plugins and the beautiful syntax is what makes jQuery such a great framework. Keep reading to know much more about it and to see why we recommend it.

Getting started

To use jQuery, you need to include it on the pages where you wish to take advantage of it. You can do this by downloading jQuery from their website at www.jquery.com. There is usually a choice between a "Production" version and a "Development" version. The first is for your live website, because it has been minified and compressed to take up the least amount of space, which is important for your visitors, whose browser will have to download the jQuery file along with the rest of your website. For testing and development, the "Development" version is best. It hasn't been minified or compressed, so when you run into an error, you can actually see where in jQuery it happens.

Once downloaded, you will have to reference the jQuery JavaScript file on your pages, using the <script> HTML tag. The easiest way is to place the downloaded jquery.js file in the same directory as the page from where you wish to use it and then reference it like this, in the section of your document:

<script type="text/javascript" src="jquery-1.5.1.js"></script>

A part of your page should now look something like this:

<head>
        <title>jQuery test</title>
        <script type="text/javascript" src="jquery-1.5.1.js"></script>
</head>

A more modern approach, instead of downloading and hosting jQuery yourself, is to include it from a CDN (Content Delivery Network). Both Google and Microsoft host several different versions of jQuery and other JavaScript frameworks. It saves you from having to download and store the jQuery framework, but it has a much bigger advantage: Because the file comes from a common URL that other websites may use as well, chances are that when people reaches your website and their browser requests the jQuery framework, it may already be in the cache, because another website is using the exact same version and file. Besides that, most CDN's will make sure that once a user requests a file from it, it's served from the server closest to them, so your European users won't have to get the file all the way from the US and so on.

You can use jQuery from a CDN just like you would do with the downloaded version, only the URL changes. For instance, to include jQuery 1.5.1 from Google, you would write the following:

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

I suggest that you use this approach, unless you have a specific reason for hosting jQuery yourself. Here is a link to the jQuery CDN information from Google:

http://code.google.com/intl/da/apis/libraries/devguide.html#jquery

Or if you prefer to use it from Microsoft:

http://www.asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

Read on to learn how to start using jQuery.

Hello, world!

Every decent programming tutorial will start with a "Hello, world!" example and this tutorial is yet another one of them. In the previous chapter, we learned how to include jQuery on our page, so that we may start using all of its great features. You need to know a bit more about how jQuery works, before you can start writing your own code, but just to make sure that everything is working, and for you to see how simple jQuery is, let's kick off with a little example:

<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>

Okay, so we have a div tag with the id of "divTest1". In the JavaScript code we use the $ shortcut to access jQuery, then we select all elements with an id of "divTest1" (there is just one though) and set its text to "Hello, world!". You may not know enough about jQuery to understand why and how this works, but as you progress through this tutorial, all of the elements will be explained in detail.

Even such a simple task as this one would actually require quite a few extra keystrokes if you had to do it in plain JavaScript, with no help from jQuery:

<div id="divTest2"></div>
<script type="text/javascript">
document.getElementById("divTest2").innerHTML = "Hello, world!";
</script>

And it would be even longer if our HTML element didn't have an ID, but for instance just a class.

Normally though, you wait for the document to enter the READY state before you start manipulating its content. The above examples will work in most browsers and likely even work when you do more advanced stuff, but certain tasks may fail if you try to do them before the document is loaded and ready. Fortunately, jQuery makes this very easy as well, as we will see in the next chapter. After that, we will start looking into one of the most important aspects of jQuery, which has already been used in the above example: Selectors.

The ready event

As mentioned in the previous chapter, it's 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, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the "Hello, world!" chapter, but this time the code is inside the ready event:

<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#divTest1").text("Hello, world!");  
}

$(document).ready(DocumentReady);
</script>

What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:

<div id="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#divTest2").text("Hello, world!");  
});
</script>

But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:

<div id="divTest3"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest3").text("Hello, world!");  
});
</script>

In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.

Method chaining

Yet another one of the really cool aspects of jQuery is the fact that most of the methods returns a jQuery object that you can then use to call another method. This allows you to do command chaining, where you can perform multiple methods on the same set of elements, which is really neat because it saves you and the browser from having to find the same elements more than once. Here's an example, and don't worry about the jQuery methods used in the following examples - they will be explained in later chapters:

<div id="divTest1"></div>
<script type="text/javascript">
        $("#divTest1").text("Hello, world!").css("color", "blue");
</script>

It works like this: We instantiate a new jQuery object and select the divTest1 element with the $ character, which is a shortcut for the jQuery class. In return, we get a jQuery object, allowing us to manipulate the selected element. We use that object to call the text() method, which sets the text of the selected element(s). This method returns the jQuery object again, allowing us to use another method call directly on the return value, which is the css() method.

We can add more method calls if needed, but at some point, the line of code will become quite long. Fortunately for us, JavaScript is not very strict when it comes to the syntax, so you can actually format it like you want, including linebreaks and indentations. For instance, this will work just fine as well:

<div id="divTest2"></div>
<script type="text/javascript">
        $("#divTest2").text("Hello, world!")
                                        .removeClass("blue")
                                        .addClass("bold")
                                        .css("color", "blue");                                  
</script>

JavaScript will simply throw away the extra whitespace when interpreting the code and execute it as one long line of code with several method calls.

Note that some methods doesn't return the jQuery object, while others only return it depending on the parameters you pass to it. A good example of that is the text() method used above. If no parameters are passed to it, the current text of the selected element(s) is returned instead of a jQuery object, while a single parameter causes jQuery to set the specified text and return a jQuery object.

Introduction to jQuery selectors

A very common task when using JavaScript is to read and modify the content of the page. To do this, you need to find the element(s) that you wish to change, and this is where selector support in jQuery will help you out. With normal JavaScript, finding elements can be extremely cumbersome, unless you need to find a single element which has a value specified in the ID attribute. jQuery can help you find elements based on their ID, classes, types, attributes, values of attributes and much, much more. It's based on CSS selectors and as you will see after going through this tutorial, it is extremely powerful.

Because this is such a common task, the jQuery constructor comes in several forms that takes a selector query as an argument, allowing you to locate element(s) with a very limited amount of code for optimal efficiency. You can instantiate the jQuery object simply by writing jQuery() or even shorter using the jQuery shortcut name: $(). Therefore, selecting a set of elements is as simple as this:

$(<query here>)

With the jQuery object returned, you can then start using and altering the element(s) you have matched. In the following chapters, you will see examples of some of the many ways you can select elements with jQuery.

Using elements, ID's and classes

The #id selector


A very common selector type is the ID based, which we saw in the "Hello, world" example. It uses the ID attribute of a HTML tag to locate the desired element. An ID should be unique, so you should only use this selector when you wish to locate a single, unique element. To locate an element with a specific ID, write a hash character, followed by the ID of the element you wish to locate, like this:
$("#divTest")

An example of it in use:

<div id="divTest"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest").text("Test");
});
</script>

Now, while there is only a single element that matches our query above, you should be aware that the result is a list, meaning that it can contain more than one element, if the query matches more than one. A common example of this is to match all elements which uses one or several CSS classes.

The .class selector


Elements with a specific class can be matched by writing a . character followed by the name of the class. Here is an example:

<ul>
        <li class="bold">Test 1</li>
        <li>Test 2</li>
        <li class="bold">Test 3</li>
</ul>
<script type="text/javascript">
$(function()
{
        $(".bold").css("font-weight", "bold");
});
</script>

The element selector


You can also match elements based on their tag names. For instance, you can match all links on a page like this:

$("a")

Or all div tags like this:

$("div")

If you use a multi-element selector, like the class selector we used in the previous example, and we know that we're looking for elements of a specific type, it's good practice to specify the element type before the selector. Not only is it more precise, it's also faster for jQuery to process, resulting in more responsive sites. Here is a re-written version of the previous example, where we use this method:
$("span.bold").css("font-weight", "bold");

This will match all span elements with "bold" as the class. Of course, it can be used with ID's and pretty much all of the other selectors as well.

Selectors can do much more for you though. Read on for more cool examples.

Using attributes

In the previous chapter, we saw how we could find elements in a page from their class or their ID. These two properties are related because of the fact that you can use them to style the elements with CSS, but with jQuery, you can actually find elements based on any kind of attribute. It comes with a bunch of attribute selector types and in this article, we will look into some of them.

Find elements with a specific attribute


The most basic task when selecting elements based on attributes is to find all the elements which has a specific attribute. Be aware that the next example doesn't require the attribute to have a specific value, in fact, it doesn't even require it to have a value. The syntax for this selector is a set of square brackets with the name of the desired attribute inside it, for instance [name] or [href]. Here is an example:

<span title="Title 1">Test 1</span><br />
<span>Test 2</span><br />
<span title="Title 3">Test 3</span><br />

<script type="text/javascript">
$(function()
{
        $("[title]").css("text-decoration", "underline");
});
</script>

We use the attribute selector to find all elements on the page which has a title attribute and then underline it. As mentioned, this will match elements with a title element no matter what their value is, but sometimes you will want to find elements with a specific attribute which has a specific value.

Find elements with a specific value for a specific attribute


Here's an example where we find elements with a specific value:

<a href="http://www.google.com" target="_blank">Link 1</a><br />
<a href="http://www.google.com" target="_self">Link 2</a><br />
<a href="http://www.google.com" target="_blank">Link 3</a><br />

<script type="text/javascript">
$(function()
{
        $("a[target='_blank']").append(" [new window]");
});
</script>

The selector simply tells jQuery to find all links (the a elements) which has a target attribute that equals the string value "_blank" and then append the text "[new window]" to them. But what if you're looking for all elements which don't have the value? Inverting the selector is very easy:
$("a[target!='_blank']").append(" [same window]");

The difference is the != instead of =, a common way of negating an operator within many programming languages.

And there's even more possibilities:

Find elements with a value which starts with a specific string using the ^= operator:
$("input[name^='txt']").css("color", "blue");

Find elements with a value which ends with a specific string using the $= operator:
$("input[name$='letter']").css("color", "red");

Find elements with a value which contains a specific word:
$("input[name*='txt']").css("color", "blue");

Parent/child relation selectors

jQuery also allows you to select elements based on their parent element. There are two variations: One which will only match elements which are a direct child to the parent element, and one which will match all the way down through the hierarchy, e.g. a child of a child of a child of a parent element.

The syntax for finding children which are direct descendants of an element looks like this:

$("div > a")

This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:

$("div a")

Here's an example where we color bold tags blue if they are directly descending from the first test area:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 > b").css("color", "blue");
</script>

As you will see, only the first bold tag is colored. Now, if you had used the second approach, both bold tags would have been colored blue. Try the following example, where the only thing changed is the greater-than character which has been replaced with a space, to note that we also accept non-direct descendants or "grand children" as they are sometimes called:

<div id="divTestArea1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTestArea2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>

<script type="text/javascript">
$("#divTestArea1 b").css("color", "blue");
</script>

Now the cool thing is that you can actually go back up the hierarchy if needed, using the parent() method. We'll look into that in another chapter of this tutorial.

Fading elements

Doing simple animation is very easy with jQuery. One of the effects it supports out-of-the-box, is fading an element in and out of visibility. Here's a simple example, where we fade in an otherwise hidden box, using the fadeIn() method:



<div id="divTestArea1" style="padding: 50px;
background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
        $("#divTestArea1").fadeIn();
}
</script>

You can fade a lot of different elements, like divs, spans or links. The fadeIn() method can take up to three parameters. The first one allows you to specify the duration of the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds. Here's an example of it in use:



<div id="divTestArea21" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px; display: none;
background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px; display: none;
background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
        $("#divTestArea21").fadeIn("fast");
        $("#divTestArea22").fadeIn("slow");
        $("#divTestArea23").fadeIn(2000);
}
</script>

Don't mind all the HTML, it's just there so that you can see the difference between the fading durations. Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the fadeOut() method, which obviously has the reverse effect of fadeIn():



<div id="divTestArea3" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").fadeIn(2000, function()
        {
                $("#divTestArea3").fadeOut(3000);
        });
});
</script>

There may be situations where you want to fade an element in our out depending on its current state. You could of course check if it is visible or not and then call either fadeIn() or fadeOut(), but the nice jQuery developers have supplied us with a specific method for toggling an element, called fadeToggle(). It takes the same parameters as fadeIn() and fadeOut(), so it's very easy to use. Here's a little example:



<div id="divTestArea4" style="width: 50px; height: 50px; display: none;
background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
        $("#divTestArea4").fadeToggle("slow");  
}
</script>

And that's how easy it is to use the fading effects of jQuery.

Sliding elements

In the previous chapter, we saw how we could fade elements in and out of visibility using the fading methods of jQuery. However, sometimes a sliding effect is a better choice, and for that, jQuery has a set of matching methods for doing just that. Let's kick off with a simple example of it, where we use the slideDown() method:

<div id="divTestArea1" style="padding: 50px;
background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>
<a href="javascript:void(0);" onclick="ShowBox();">Show box</a>
<script type="text/javascript">
function ShowBox()
{
        $("#divTestArea1").slideDown();
}
</script>

For hiding the box again, we can use the slideUp() method. They both take the same set of parameters, which are all optional. The first parameter allows you to specify a duration for the effect in milliseconds, or "fast" or "slow", which is the same as specifying either 200 or 600 milliseconds.Let's try an example where we do just that:

<div id="divTestArea21" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div>
<div id="divTestArea22" style="width: 50px; height: 50px;
display: none; background-color: #C3D1DF;"></div>
<div id="divTestArea23" style="width: 50px; height: 50px;
display: none; background-color: #9966FF;"></div>
<a href="javascript:void(0);" onclick="ShowBoxes();">Show boxes</a>
<script type="text/javascript">
function ShowBoxes()
{
        $("#divTestArea21").slideDown("fast");
        $("#divTestArea22").slideDown("slow");
        $("#divTestArea23").slideDown(2000);
}
</script>

There's a bit more HTML than usual, but that's only there for you to be able to see the different paces in which the boxes are shown. Notice how the first box is there almost instantly, the second box is pretty close and the third box is slower, because it uses a full two seconds to slide down.

Now, the second parameter can either be the name of an easing function (which we won't use in this tutorial) or a callback function that you may supply, to be called once the effect is done. Here's an example of that, combined with the use of the slideUp() method:

<div id="divTestArea3" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").slideDown(2000, function()
        {
                $("#divTestArea3").slideUp(3000);
        });
});
</script>

The ability to do this can be very useful for combining several effects, as you can see. In this example, the callback function we supply will be called as soon as the slideDown() method is completely finished and then the slideUp() method is called.

In case you want to simply slide an element up or down depending on its current state, the jQuery developers have provided us with a nice slideToggle() method for doing just that. Check out the next example, where we use it:

<div id="divTestArea4" style="width: 50px; height: 50px;
display: none; background-color: #89BC38;"></div><br />
<a href="javascript:void(0);" onclick="ToggleBox();">Toggle box</a>
<script type="text/javascript">
function ToggleBox()
{
        $("#divTestArea4").slideToggle("slow");
}
</script>

Custom animations with the animate() method

In previous chapters, we looked into the built-in fading and sliding effect methods of jQuery. However, you can much more than just that. With the animate() method, you can create custom animations where you manipulate pretty much any numerical CSS property of an element. This allows you to e.g. move a box slowly across the screen or have it jump up and down. Let's try something very simple:

<div style="height: 60px;">
        <div id="divTestBox1" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox1").animate(
                {
                        "left" : "200px"
                }
        );
});
</script>

The first, and only required, parameter of the animate function is a map of the CSS properties that you wish to have altered. In this case, we have an absolutely positioned div element, which we tell jQuery to move until it has reached a left property of 200 pixels.
The second parameter allows you to specify the duration of the animation in milliseconds or as "slow" or "fast" which is the same as 600 or 200 ms. With this, we can slow down the above example as much as we want:

<div style="height: 60px;">
        <div id="divTestBox2" style="height: 50px; width: 50px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox2").animate(
                {
                        "left" : "200px"
                },
                5000
        );
});
</script>

As the third parameter, we can specify a callback function to be called once the animation is done. This can be very useful for performing a number of different animations in a row. For instance, check out this example:

<div style="height: 40px;">
        <div id="divTestBox3" style="height: 20px; width: 20px;
background-color: #89BC38; position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox3").animate(
                { "left" : "100px" },
                1000,
                function()
                {
                        $(this).animate(
                                { "left" : "20px" },
                                500,
                                function()
                                {
                                $(this).animate({ "left" : "50px" }, 500);
                                }
                        )
                }
        );
});
</script>

It might seem a bit overwhelming, but what we do is that we call the animate method and ask for the left property of our test "div" to be animated until it reaches a left of 100 pixels. We want it to take 1 second (1000 milliseconds) and once it completes, we wish for a new animation to start, which moves it back to 20 pixels within half a second, and as soon as THAT animation is done, we move it a bit right again, so that it now has a left property of 50 pixels.

However, since jQuery comes with queue functionality for animations, you can actually achieve the above example in a much simpler manner. This however only applies when you want a set of animations to performed after each other - if you want to do something else when an animation is complete, the above example will still be the way to go. Here's the queue version:

<div style="height: 40px;">
<div id="divTestBox4" style="height: 20px; width: 20px; background-color: #89BC38;
position: absolute;"></div>
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestBox4").animate({ "left" : "100px" }, 1000);
        $("#divTestBox4").animate({ "left" : "20px" }, 500);
        $("#divTestBox4").animate({ "left" : "50px" }, 500);
});
</script>

Stopping animations with the stop() method

In the previous chapter, we saw how we could do custom animations using the animate() method and how we could have several animations after each other, by making several animation calls and thereby using the animation queue of jQuery. However, sometimes you need to stop an animation before it finishes, and for this, jQuery has the stop() method. It works for all effects related jQuery functions, including sliding, fading and custom animations with the animate() method. Here's an example where we use it:

<a href="javascript:void(0);" onclick="$('#divTestArea1').slideDown(5000);">
Show box</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea1').stop();">Stop</a>

<div id="divTestArea1" style="padding: 100px; background-color: #89BC38;
text-align: center; display: none;">
        <b>Hello, world!</b>
</div>

To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:

<a href="javascript:void(0);" onclick="$('#divTestArea2').slideDown(5000)
.slideUp(5000);">Show box</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea2').stop();">Stop</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea2').stop(true);">
Stop all</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea2').clearQueue().hide();">
Reset</a>

<div id="divTestArea2" style="padding: 100px; background-color: #89BC38; text-align: center; display: none;">
        <b>Hello, world!</b>
</div>

We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped.

The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:

<a href="javascript:void(0);" onclick="$('#divTestArea3').slideDown(5000);">
Show box</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true);">Stop</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea3').stop(true, true);">
Stop but finish</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea3').clearQueue().hide();">
Reset</a>

<div id="divTestArea3" style="padding: 100px; background-color: #89BC38;
text-align: center; display: none;">
        <b>Hello, world!</b>
</div>

Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.

Introduction to DOM manipulation

One of the most important aspects of JavaScript and thereby jQuery, is manipulation of the DOM. DOM stands for Document Object Model and is a mechanism for representing and interacting with your HTML, XHTML or XML documents. It allows you to navigate and manipulate your documents through a programming language, which in the browser will almost always be JavaScript. DOM navigation and manipulation using standard JavaScript can be pretty cumbersome, but fortunately for us, jQuery comes with a bunch of DOM related methods, making it all much easier.

In the first "Hello, world!" example of this tutorial, we compared the job of finding an element and setting the text of it using first jQuery and then JavaScript. This is just the tip of the iceberg though, and in the upcoming chapters you will see just how easy it is to manipulate the content of your documents with jQuery. Read on.

Getting and setting content [text(), html() and val()]

The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These three things might seem like the same thing, but they're not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for form elements and HTML is the same as text, but including any markup.

Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:

<div id="divTest">
        <b>Test</b>
        <input type="text" id="txtTest" name="txtTest" value="Input field" />
</div>

<script type="text/javascript">
$(function()
{
        alert("Text: " + $("#divTest").text());
        alert("HTML: " + $("#divTest").html());
        alert("Value: " + $("#divTest").val());

        alert("Text: " + $("#txtTest").text());
        alert("HTML: " + $("#txtTest").html());
        alert("Value: " + $("#txtTest").val());
});
</script>

So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:

<div id="divText"></div>
<div id="divHtml"></div>
<input type="text" id="txtTest" name="txtTest" value="Input field" />

<script type="text/javascript">
$(function()
{
        $("#divText").text("A dynamically set text");
        $("#divHtml").html("<b><i>A dynamically set HTML string</i></b>");
        $("#txtTest").val("A dynamically set value");
});
</script>

And that's how easy it is to set text, HTML and values.

These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:

<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>

<script type="text/javascript">
$(function()
{
        $("p").text(function(index, oldText) {
                return "Existing text: " + oldText + ". New text:
A dynamically set text (#" + index + ")";
        });
});
</script>

We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.

Getting and setting attributes [attr()]

In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:

<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
        alert($("#aGoogle1").attr("href"));
});
</script>

In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:

<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>

This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:

<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle3").attr(
        {
                "href" : "http://www.google.co.uk",
                "title" : "Google.co.uk"
        });
});
</script>

The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:

<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />

<script type="text/javascript">
$(function()
{
        $("a.google").attr("href", function(index, oldValue)
        {
                return oldValue + "imghp?tab=wi";
        });
});
</script>

We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.

Getting and setting CSS classes

Just like it's very easy to manipulate content and attributes of elements, as we saw in the previous chapters, it's equally easy to manipulate the CSS of elements. jQuery gives you easy access to changing both the style attribute, which you manipulate using the css() method, as well as the class(es) of an element, where several different methods lets you modify it.

Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).

I have defined a couple of very simple CSS selectors in my stylesheet, mostly for testing purposes:
.bold {
        font-weight: bold;
}

.blue {
        color: blue;
}

In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.

<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a>

<script type="text/javascript">
function ToggleClass(sender)
{

        if($(sender).hasClass("bold"))
                $(sender).removeClass("bold");
        else
                $(sender).addClass("bold");
}
</script>

The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:

<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">
Toggle class</a>

Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:

<div id="divTestArea1">
        <span>Test 1</span><br />
        <div>Test 2</div>
        <b>Test 3</b><br />
</div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea1 span, #divTestArea1 b").addClass("blue");
        $("#divTestArea1 div").addClass("bold blue");
});
</script>

First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space.

The append() and prepend() methods

Adding new stuff to existing elements is very easy with jQuery. There are methods for appending or prepending, taking HTML in string format, DOM elements and jQuery objects as parameters. In the next example, you will see how easy it is to insert new elements in a list, using both the append() and the prepend() method:

<a href="javascript:void(0);" onclick="$('#olTestList1')
.append('<li>Appended item</li>');">Append</a>  
<a href="javascript:void(0);" onclick="$('#olTestList1')
.prepend('<li>Prepended item</li>');">Prepend</a>

<ol id="olTestList1">
        <li>Existing item</li>
        <li>Existing item</li>
</ol>

We have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:

<a href="javascript:void(0);" onclick="AppendItemsToList();">Append items</a>  
<ol id="olTestList2"></ol>

<script type="text/javascript">
function AppendItemsToList()
{
        var item1 = $("<li></li>").text("Item 1");
        var item2 = "<li>Item 2</li>";
        var item3 = document.createElement("li");
        item3.innerHTML = "Item 3";

        $("#olTestList2").append(item1, item2, item3);
}
</script>

As you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too.

There are variations of the append() and prepend() methods, called appendTo() and prependTo(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to append/prepend to, with a parameter of what is to be appended/prepended, you do the exact opposite. Which to use obviously depends on the situation, but here's an example showing you how to use them both:

<a href="javascript:void(0);" onclick="PrependItemsToList();">Prepend items</a>  
<ol id="olTestList3"></ol>

<script type="text/javascript">
function PrependItemsToList()
{      
        $("#olTestList3").prepend($("<li></li>").text("prepend() item"));
        $("<li></li>").text("prependTo() item").prependTo("#olTestList3");
}
</script>

In this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs.

The before() and after() methods

In the previous chapter, we used the append() and prepend() methods to insert stuff inside an element, but in some cases, you need to insert things before or after one or several elements instead. jQuery has the before() and after() methods for just this purpose, and they are just as easy to use. Check out this example:

<a href="javascript:void(0);" onclick="$('input.test1')
.before('<i>Before</i>');">Before</a>  
<a href="javascript:void(0);" onclick="$('input.test1')
.after('<b>After</b>');">After</a>

<br /><br />

<input type="text" class="test1" value="Input 1" name="txtInput1" /><br />
<input type="text" class="test1" value="Input 2" name="txtInput2" /><br />

Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:

<a href="javascript:void(0);" onclick="InsertElements();">Insert elements</a>
<br /><br />
<span id="spnTest2">Hello world? </span>

<script type="text/javascript">
function InsertElements()
{
        var element1 = $("<b></b>").text("Hello ");
        var element2 = "<i>there </i>";
        var element3 = document.createElement("u");
        element3.innerHTML = "jQuery!";

        $("#spnTest2").after(element1, element2, element3);
}
</script>

In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.

There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both:

<a href="javascript:void(0);" onclick="InsertElementsBefore();">
Insert elemenets</a>
<br /><br />
<span id="spnTest3">Hello world? </span>

<script type="text/javascript">
function InsertElementsBefore()
{      
        $("#spnTest3").before($("<i></i>").text("before() "));
        $("<b></b>").text("insertBefore() ").insertBefore("#spnTest3");
}
</script>

In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs.

The remove() and empty() methods

In the last couple of chapters, we have worked with adding new elements to a page, but of course jQuery can help you remove them as well. There are mainly two methods for this: remove() and empty(). The remove() method will delete the selected element(s), while the empty() method will only delete all child elements of the selected element(s). The following example should illustrate the difference - be sure to click the links in the right order though:

<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">
empty() div</a>  
<a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">
remove() div</a>
<div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b>
        <i>Italic text</i>
</div>

The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.

The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:

<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">
remove() more bold</a>
<div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px;
border: 1px solid silver; background-color: #eee;">
        <b>Bold text</b><br />
        <b class="more">More bold text</b><br />
        <b class="more">Even more bold text</b><br />
</div>

We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.

You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.

Introduction to events

Events in JavaScript are usually something where you write a snippet of code or a name of a function within one of the event attributes on an HTML tag. For instance, you can create an event for a link by writing code like this:

<a href="javascript:void(0);" onclick="alert('Hello, world!');">Test</a>

And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
<script type="text/javascript">
$(function()
{
        $("a, span").bind("click", function() {
                alert('Hello, world!');
        });
});
</script>

We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.

The bind() method

One of the most important aspects of dealing with events through jQuery is the bind() and unbind() methods. As the names imply, they will simply attach and unattach code to one or several events on a set of elements. We saw a very simple usage example for the bind() method in the introduction chapter for events, and here is a more complete one:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
$(function()
{
        $("a").bind("click", function() {
                alert($(this).text());
        });
});
</script>

It works by selecting all links (<a> elements) and then bind the anonymous function you see to the click event. A cool little feature is that jQuery will automatically assign the element that is clicked, to the "this" keyword inside of the anonymous function. This will allow you to access the element that activates the element, even when you assign the same code to multiple elements.

When jQuery calls your method, it will pass information about the event as the first parameter, if you have specified one or more parameters on it. For instance, the event object passed will contain information about where the mouse cursor is, which type the event is, which keyboard key or mouse button was pressed (if any) and much more. You can see all the properties and methods on the event object here: http://api.jquery.com/event.which/

Here is an example:

<div id="divArea" style="background-color: silver; 
width: 100px; height: 100px;">
</div>
<script type="text/javascript">
$("#divArea").bind("mousemove", function(event)
{
        $(this).text(event.pageX + "," + event.pageY);
});
</script>

We create a div element of a reasonable size and a background color. For this div, we subscribe to the mousemove event, with an anonymous function with a parameter called "event". This object gives us access to the pageX and pageY properties, which tells us where on the page the mouse cursor currently is, relative to the top left corner of the document. Try the example and move the cursor over the div element and you will see the coordinates updated as you move the mouse.

The bind() method also allows you to pass in data of your own and access it from the event object. This also allows you to set values at the time you bind the event, and be able to read this value at the time the event is invoked, even though the original variable you used may have changed. Here's an example where you can see just that:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", { message : msg }, function(event) {
                msg = "Changed msg";
                alert(event.data.message);
        });
});
</script>

We pass the value as the secondary parameter of the bind() method, as a map of keys and values. You can pass more than one value by separating them with a comma. To access the value inside the event handler, we use the data property of the event object. This property contains sub-properties for each of the values you have passed, which means that you can access the value of the message parameter using event.data.message.

Despite the fact that we change the value of the "msg" variable inside the event handler, the message displayed will still be "Hello, world!" every time you click on one of the links, because it's evaluated as soon as the event handler is bound, which is once the page has been loaded.

The unbind() method

In the previous chapter, we used the bind() method to subscribe to events with jQuery. However, you may need to remove these subscriptions again for various reasons, to prevent the event handler to be executed once the event occurs. We do this with the unbind() method, which in its simplest form simply looks like this:

$("a").unbind();

This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks:

$("a").unbind("click doubleclick");

Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", function() {
                $("a").unbind("click");
                alert("First and only message from me!");
        });
});
</script>

In this little example, we subscribe to the click event of all links. However, once a link is clicked, we remove all the subscriptions and alert the clicker about it. The event handler will no longer be activated by the links.

jQuery allows you to subscribe to the same event type more than one time. This can come in handy if you want the same event to do more than one thing in different situations. You do it by calling the bind() method for each time you want to attach a piece of code to it, like this:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", function() {
                alert("First event handler!");
        });

        $("a").bind("click", function() {
                alert("Second event handler!");
                $("a").unbind("click");
        });
});
</script>

However, this opens up for the possibility that once you unbind an event, you may be removing event subscriptions used a whole other place in your code, which you still need. If you try the example, you will see the result of this - when you click a link, all of the event subscriptions are removed. jQuery allows you to specify a secondary argument, which contains a reference to the specific handler you would like to remove. This way, we can make sure that we only remove the event subscription we intend to. Here's an example:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        var handler1 = function()
        {
                alert("First event handler!");
        }

        var handler2 = function()
        {
                alert("Second event handler!");
                $("a").unbind("click", handler2);
        }

        $("a").bind("click", handler1);
        $("a").bind("click", handler2);
});
</script>

By specifying handler2 as the secondary parameter, only this specific event handler is removed. Try the example. The secondary message is only displayed the first time you click the link.

The live() method

In the previous chapters, we used the bind() and unbind() methods to attach and detach event handlers to various elements on the page. This works great for elements which already exists, but what if you want your event handler to be attached to future elements as well? Normally you would have to do this manually, upon creating the new elements, and this is still possible. However, using the live() method, you can inform jQuery to attach your event handler to any future elements which matches your original selector, without having to lift a finger. Let me first show you an example where we use the bind() method, and then replace it with the live() method, to show you the difference:

<div id="divTestArea1">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").bind("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).bind("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea1").append(div);
}
</script>

Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.

Now try the following example instead. I have only changed two words in it: The two calls to bind() has been replaced with calls to live():

<div id="divTestArea2">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").live("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).live("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea2").append(div);
}
</script>

Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used.

Introduction to AJAX

AJAX, short for Asynchronous JavaScript And XML, allows you to load data in the background and display it on your webpage, without refreshing the page. This allows you to create websites with much richer functionality. Popular web applications like Gmail, Outlook Web Access, and Google Maps uses AJAX extensively, to provide you with a more responsive, desktop-like experience.

Using AJAX can be a bit cumbersome, because the various browsers have different implementations to support AJAX. Normally this would force you to write code to respond differently, depending on the browser, but fortunately, jQuery has done this for us, which allows us to write AJAX functionality with as little as a single line of code.

You should be aware of the fact that thre are both advantages and disadvantages to using AJAX on your page though, which means that you should always consider carefully before deciding to use it instead of doing a regular postback to the server. Here's a summary:

Advantages



  • Your page will be more pleasant to use, when you can update parts of it without a refresh, which causes the browser to flicker and the statusbar to run.

  • Because you only load the data you need to update the page, instead of refreshing the entire page, you save bandwidth.


Disadvantages



  • Because the updates are done by JavaScript on the client, the state will not register in the browsers history, making it impossible to use the Back and Forward buttons to navigate between various states of the page.

  • For the same reason, a specific state can't be bookmarked by the user.

  • Data loaded through AJAX won't be indexed by any of the major search engines.

  • People using browsers without JavaScript support, or with JavaScript disabled, will not be able to use the functionality that you provide through AJAX.


The first two items on the list may be circumvented though, typically through the use of an iframe and reading and writing data from the part of the URL after the # character.

In the following chapters, you will learn how to use various AJAX related functions of jQuery.

The load() method

As described in the previous chapter, there are many ways to use AJAX with jQuery, and they should of course be used depending on the situation. One of the simplest and yet still powerful methods for loading data asynchronously is the load() method. You use it by selecting an element where you want the content loaded to and then call the load() method on it. It takes the URL that you wish to load, as a parameter. For this example, we need a an external file that we can load. We'll call it content.html and the content of it should look something like this:
<div id="divContent">
        <b>This is external content</b>
</div>
And there's more of it

Save it as content.html, in the same directory where you keep your other example files for this tutorial. We can load it as simple as this:

<div id="divTestArea1"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea1").load("content.html");
});
</script>

If you have the content file in another directory, or if you have named it differently, you will have to change the parameter for the load method accordingly. This is all it takes to load content from an external file with jQuery and the load method. A pretty cool trick is that you can actually pass a selector along with the URL, to only get a part of the page. In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence:

<div id="divTestArea2"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea2").load("content.html #divContent");
});
</script>

As you can see, we simply append a standard jQuery selector to the parameter, after the URL, separated with a space. This causes jQuery to select the content out and only pass the matched part(s) back to the container. You can use any jQuery selector type to pull off this trick, which makes it pretty powerful.

The load method can take two extra parameters: A set of querystring key/value pairs, and a callback function which will be executed when the load method finishes, no matter if it succeeds or fails. Here is an example where we use the callback function to inform about the result. Normally, you would likely only show a message if the method fails, but to illustrate how it works, we do it if the method fails as well. I make sure that it fails for the example, by requesting a file which doesn't exist:

<div id="divTestArea3"></div>
<script type="text/javascript">
$(function()
{
        $("#divTestArea3").load("no-content.html",
function(responseText, statusText, xhr)
        {
                if(statusText == "success")
                        alert("Successfully loaded the content!");
                if(statusText == "error")
       alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
        });
});
</script>

As you can see, the callback function specifies 3 parameters, which jQuery will fill in for you. The first parameter will contain the resulting content if the call succeeds. The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. The third parameter is the XMLHttpRequest object used to perform the AJAX call. It will contain properties which you can use to see what went wrong and many other things.

The get() and post() methods

The jQuery get() and post() methods allows you to easily send a HTTP request to a page and get the result back. When you post a form, it's usually either a GET or a POST request, and with jQuery you can mimic that, since both a get() and a post() method exists.

The two methods are pretty much identical, since they simply just invoke different request types against the server. They are both static methods, which means that instead of instantiating a jQuery object and then working with that, we call get() or post() directly on the jQuery class, either by writing jQuery.get() or by using the shortcut character like this: $.get(). In its most simple form, the get() and post() methods takes a single parameter, which is the URL that you wish to request. However, in most cases you will want to do something with the returned data, in which case you can pass a callback function as a parameter, which jQuery will call if the request succeeds.

Let's do some testing. In the previous chapter, I created an HTML file called "content.html", which we loaded using the jQuery load() method. When testing the following example, make sure that you have a file called "content.html" in the same directory as the file in which you have the example. The content doesn't really matter, just write anything in there really. Here's an example of the get() method:
<script type="text/javascript">
$(function()
{
        $.get("content.html", function(data, textStatus)
        {
                alert("Done, with the following status: "
+ textStatus + ". Here is the response: " + data);
        });
});
</script>


The first parameter is the URL, which is just content.html. The second parameter is more interesting. It's a callback function, which jQuery calls if the page request succeeds. The first callback parameter is simply the content of the page requested, while the second callback parameter is the textual status of the request.

You can of course request a simple HTML page, like in the example above, but normally the reason for using a GET or a POST request is that you wish to pass in some parameters, which is then processed by the server, for instance with a piece of PHP, ASP or ASP.NET code, and then return the result. jQuery can take a map of GET or POST parameters, which we will try in the following example, where we use the post() method:

<script type="text/javascript">
$(function()
{
        $.post("test_post.php",
        {
                name: "John Doe",
                age: "42"
        },
        function(data, textStatus)
        {
                alert("Response from server: " + data);
        });
});
</script>


This example is much like the first one, but we make the POST request to another page, in this example a PHP page, and as the second parameter, we pass in a map of POST parameters. The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting an URL like this in your browser:

test_get.php?name=John Doe&age=42

The PHP script can then read the parameters, process them and return a result. The script on our server simply takes the two values and creates a string like "is years old" and then returns it, which you can see if you test the example above.

Same Origin Policy

Same Origin Policy is a security feature found in the JavaScript implementation in most browsers, as well as in other technologies used in a browser, e.g. Flash. It basically allows you to make requests to pages within the same site/domain, while preventing you from making requests to pages on a different domain, another subdomain or through a different protocol. Since this is a part of JavaScript, it's also a part of jQuery, as you will see if you try to do an AJAX call to a page on another domain - it's simply not possible. There are certain hacks and workarounds to circumvent Same Origin Policy, but they usually don't work in all browsers or have other problems.

However, sometimes you really do need to make requests to a page on a different domain, especially in cases where you own both domains or when the owner of the secondary domain would like for you to access the page. Fortunately, the JSONP standard allows us to do just this, and while it's also a bit of a hack that would require quite a bit of effort to use within JavaScript, jQuery supports this very elegantly, allowing you to do JSONP based calls just as easy as a regular AJAX call. In fact, you can change the get() or post() call to be JSONP based simply by stating that you would like the return type to be "json".

JSON, short for JavaScript Object Notation, is a data notation, a bit like XML, allowing you to transfer structured data easily, usually over a network connection. Despite the fact that it was originally intended to use with JavaScript, a lot of other programming languages supports it out-of-the-box as well, allowing you to easily output arrays and objects in the JSON format.

In the next chapter, we will create an example where we use the JSONP technique to request a file on a different subdomain.