Python Environment

Python Environment

Try it Option

You really do not need to set up your own environment to start learning Python programming language. Reason is very simple, we already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

Try following example using Try it option available at the top right corner of the below sample code box:

#!/usr/bin/python

 

print "Hello, Python!";

For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.

Local Environment Setup

If you are still willing to set up your environment, let's understand how to set up our Python environment. Python is available on a wide variety of platforms including Linux and Mac OS X. Try opening a terminal window and type "python" to find out if its already installed and which version you have if it is installed.

Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)

Win 9x/NT/2000

Macintosh (Intel, PPC, 68K)

OS/2

DOS (multiple versions)

PalmOS

Nokia mobile phones

Windows CE

Acorn/RISC OS

BeOS

Amiga

VMS/OpenVMS

QNX

VxWorks

Psion

Python has also been ported to the Java and .NET virtual machines

Getting Python:

The most up-to-date and current source code, binaries, documentation, news, etc. is available at the official website of Python:

Python Official Website :http://www.python.org/

You can download Python documentation from the following site. The documentation is available in HTML, PDF and PostScript formats.

Python Documentation Website :www.python.org/doc/

Install Python:

Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.

If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.

Here is a quick overview of installing Python on various platforms:

Unix & Linux Installation:

Here are the simple steps to install Python on Unix/Linux machine.

Open a Web browser and go tohttp://www.python.org/download/

Follow the link to download zipped source code available for Unix/Linux.

Download and extract files.

Editing the Modules/Setup file if you want to customize some options.

run ./configure script

make

make install

This will install python in a standard location/usr/local/bin and its libraries are installed in/usr/local/lib/pythonXX where XX is the version of Python that you are using.

Windows Installation:

Here are the steps to install Python on Windows machine.

Open a Web browser and go tohttp://www.python.org/download/

Follow the link for the Windows installerpython-XYZ.msi file where XYZ is the version you are going to install.

To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Just save the installer file to your local machine and then run it to find out if your machine supports MSI.

Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you're ready to roll!

Macintosh Installation:

Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available."

Jack Jansen maintains it and you can have full access to the entire documentation at his Web site - Jack Jansen Website :http://www.cwi.nl/~jack/macpython.html

Just go to this link and you will find complete installation detail for Mac OS installation.

Setting up PATH:

Programs and other executable files can live in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.

The path is stored in an environment variable, which is a named string maintained by the operating system. These variables contain information available to the command shell and other programs.

The path variable is named PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not).

In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux:

To add the Python directory to the path for a particular session in Unix:

In the csh shell: type 
setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux): type 
export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell: type 
PATH="$PATH:/usr/local/bin/python" and press Enter.

Note: /usr/local/bin/python is the path of the Python directory

Setting path at Windows:

To add the Python directory to the path for a particular session in Windows:

At the command prompt : type 
path %path%;C:\Python and press Enter.

Note: C:\Python is the path of the Python directory

Python Environment Variables:

Here are important environment variables, which can be recognized by Python:

Variable

Description

PYTHONPATH

Has a role similar to PATH. This variable tells the Python interpreter where to locate the module files you import into a program. PYTHONPATH should include the Python source library directory and the directories containing your Python source code. PYTHONPATH is sometimes preset by the Python installer.

PYTHONSTARTUP

Contains the path of an initialization file containing Python source code that is executed every time you start the interpreter (similar to the Unix .profile or .login file). This file, often named .pythonrc.py in Unix, usually contains commands that load utilities or modify PYTHONPATH.

PYTHONCASEOK

Used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

PYTHONHOME

An alternative module search path. It's usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

 

Running Python:

There are three different ways to start Python:

(1) Interactive Interpreter:

You can enter python and start coding right away in the interactive interpreter by starting it from the command line. You can do this fromUnix, DOS or any other system, which provides you a command-line interpreter or shell window.

$python             # Unix/Linux

 

or

 

python%             # Unix/Linux

 

or

 

C:>python           # Windows/DOS

Here is the list of all the available command line options:

Option

Description

-d

provide debug output

-O

generate optimized bytecode(resulting in .pyo files)

-S

do not run import site to look for Python paths on startup

-v

verbose output (detailed trace on import statements)

-X

disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6

-c cmd

run Python script sent in as cmdstring

file

run Python script from given file

 

(2) Script from the Command-line:

A Python script can be executed at command line by invoking the interpreter on your application, as in the following:

$python  script.py          # Unix/Linux

 

or

 

python% script.py           # Unix/Linux

 

or

 

C:>python script.py         # Windows/DOS

Note: Be sure the file permission mode allows execution.

(3) Integrated Development Environment

You can run Python from a graphical user interface (GUI) environment as well. All you need is a GUI application on your system that supports Python.

Unix: IDLE is the very first Unix IDE for Python.

Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI.

Macintosh: The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary orBinHex'd files.

Before proceeding to next chapter, make sure your environment is properly set up and working perfectly fine. If you are not able to set up the environment properly, then you can take help from your system admin.

All the examples given in subsequent chapters have been executed with Python 2.4.3 version available on CentOS flavor of Linux.

 

Python Basic Syntax

Python Basic Syntax

The Python language has many similarities to Perl, C and Java. However, there are some definite differences between the languages. This chapter is designed to quickly get you up to speed on the syntax that is expected in Python.

First Python Program:

Interactive Mode Programming:

Invoking the interpreter without passing a script file as a parameter brings up the following prompt:

$ python

Python 2.4.3 (#1, Nov 11 2010, 13:34:43)

[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>>

 

Type the following text to the right of the Python prompt and press the Enter key:

>>> print "Hello, Python!";

If you are running new version of Python, then you would need to use print statement with parenthesis like print ("Hello, Python!");.However at Python version 2.4.3, this will produce following result:

Hello, Python!

Script Mode Programming:

Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

Let us write a simple Python program in a script. All python files will have extension .py. So put the following source code in a test.py file.

print "Hello, Python!";

Here, I assumed that you have Python interpreter set in PATH variable. Now, try to run this program as follows:

$ python test.py

This will produce the following result:

Hello, Python!

Let's try another way to execute a Python script. Below is the modified test.py file:

#!/usr/bin/python

 

print "Hello, Python!";

Here, I assumed that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows:

$ chmod +x test.py     # This is to make file executable

$./test.py

This will produce the following result:

Hello, Python!

Python Identifiers:

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $ and % within identifiers. Python is a case sensitive programming language. Thus,Manpower and manpower are two different identifiers in Python.

Here are following identifier naming convention for Python:

Class names start with an uppercase letter and all other identifiers with a lowercase letter.

Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private.

Starting an identifier with two leading underscores indicates a strongly private identifier.

If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Reserved Words:

The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

and

exec

not

assert

finally

or

break

for

pass

class

from

print

continue

global

raise

def

if

return

del

import

try

elif

in

while

else

is

with

except

lambda

yield

Lines and Indentation:

One of the first caveats programmers encounter when learning Python is the fact that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Both blocks in this example are fine:

if True:

    print "True"

else:

  print "False"

However, the second block in this example will generate an error:

if True:

    print "Answer"

    print "True"

else:

    print "Answer"

  print "False"

Thus, in Python all the continous lines indented with similar number of spaces would form ablock. Following is the example having various statement blocks:

Note: Don't try to understand logic or different functions used. Just make sure you understood various blocks even if they are without braces.

#!/usr/bin/python

 

import sys

 

try:

  # open file stream

  file = open(file_name, "w")

except IOError:

  print "There was an error writing to", file_name

  sys.exit()

print "Enter '", file_finish,

print "' When finished"

while file_text != file_finish:

  file_text = raw_input("Enter text: ")

  if file_text == file_finish:

    # close the file

    file.close

    break

  file.write(file_text)

  file.write("\n")

file.close()

file_name = raw_input("Enter filename: ")

if len(file_name) == 0:

  print "Next time please enter something"

  sys.exit()

try:

  file = open(file_name, "r")

except IOError:

  print "There was an error reading file"

  sys.exit()

file_text = file.read()

file.close()

print file_text

Multi-Line Statements:

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:

total = item_one + \

        item_two + \

        item_three

Statements contained within the [], {} or () brackets do not need to use the line continuation character. For example:

days = ['Monday', 'Tuesday', 'Wednesday',

        'Thursday', 'Friday']

Quotation in Python:

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.

The triple quotes can be used to span the string across multiple lines. For example, all the following are legal:

word = 'word'

sentence = "This is a sentence."

paragraph = """This is a paragraph. It is

made up of multiple lines and sentences."""

Comments in Python:

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

 

# First comment

print "Hello, Python!";  # second comment

This will produce the following result:

Hello, Python!

A comment may be on the same line after a statement or expression:

name = "Madisetti" # This is again comment

You can comment multiple lines as follows:

# This is a comment.

# This is a comment, too.

# This is a comment, too.

# I said that already.

Using Blank Lines:

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

Waiting for the User:

The following line of the program displays the prompt, Press the enter key to exit and waits for the user to press the Enter key:

#!/usr/bin/python

 

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" are being used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.

Multiple Statements on a Single Line:

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon:

import sys; x = 'foo';sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites:

A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class, are those which require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For example:

if expression :

   suite

elif expression :

   suite

else :

   suite

Command Line Arguments:

You may have seen, for instance, that many programs can be run so that they provide you with some basic information about how they should be run. Python enables you to do this with -h:

$ python -h

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...

Options and arguments (and corresponding environment variables):

-c cmd : program passed in as string (terminates option list)

-d     : debug output from parser (also PYTHONDEBUG=x)

-E     : ignore environment variables (such as PYTHONPATH)

-h     : print this help message and exit

 

[ etc. ]

You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts.

 

Python Overview

Python Overview

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages.

Python is Interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP.

Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects.

Python is Beginner's Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.

History of Python:

Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing its progress.

Python Features:

Python's feature highlights include:

Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time.

Easy-to-read: Python code is much more clearly defined and visible to the eyes.

Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain.

A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows and Macintosh.

Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.

Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.

Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient.

Databases: Python provides interfaces to all major commercial databases.

GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as Windows MFC, Macintosh and the X Window system ofUnix.

Scalable: Python provides a better structure and support for large programs than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed below:

Support for functional and structured programming methods as well as OOP.

It can be used as a scripting language or can be compiled to byte-code for building large applications.

Very high-level dynamic data types and supports dynamic type checking.

Supports automatic garbage collection.

It can be easily integrated with C, C++, COM, ActiveX, CORBA and Java.

 

Python Tutorial

Python Tutorial

Python is a general-purpose interpreted, interactive, object-oriented and high-level programming language. Python was created by Guido van Rossum in the late eighties and early nineties. Like Perl, Python source code is also now available under the GNU General Public License (GPL).

Audience

This tutorial has been designed for software programmers with a need to understand the Python programming language starting from scratch. This tutorial will give you enough understanding on Python programming language from where you can take yourself to a higher level of expertise.

Prerequisites

Before proceeding with this tutorial you should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages will help you in understanding the Python programming concepts and move fast on the learning track.

Execute Python Programs

For most of the examples given in this tutorial you will find Try it option, so just make use of it and enjoy your learning.

Try following example using Try it option available at the top right corner of the below sample code box:

#!/usr/bin/python

 

print "Hello, Python!";

 

JavaScript Form Validation

JavaScript Form Validation

Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button. If some of the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process and over burdening server.

JavaScript, provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.

Basic Validation - First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just loop through each field in the form and check for data.

Data Format Validation - Secondly, the data that is entered must be checked for correct form and value. This would need to put more logic to test correctness of data.

We will take an example to understand the process of validation. Here is the simple form toproceed :

<html>

<head>

<title>Form Validation</title>

<script type="text/javascript">

<!--

// Form validation code will come here.

//-->

</script>

</head>

<body>

 <form action="/cgi-bin/test.cgi" name="myForm" 

         onsubmit="return(validate());">

 <table cellspacing="2"cellpadding="2" border="1">

 <tr>

   <td align="right">Name</td>

   <td><input type="text" name="Name" /></td>

 </tr>

 <tr>

   <td align="right">EMail</td>

   <td><input type="text" name="EMail" /></td>

 </tr>

 <tr>

   <td align="right">Zip Code</td>

   <td><input type="text" name="Zip" /></td>

 </tr>

 <tr>

 <td align="right">Country</td>

 <td>

 <select name="Country">

   <option value="-1" selected>[choose yours]</option>

   <option value="1">USA</option>

   <option value="2">UK</option>

   <option value="3">INDIA</option>

 </select>

 </td>

 </tr>

 <tr>

   <td align="right"></td>

   <td><input type="submit" value="Submit" /></td>

 </tr>

 </table>

 </form>

 </body>

 </html>

Basic Form Validation:

First we will show how to do a basic form validation. In the above form we are callingvalidate() function to validate data whenonsubmit event is occurring. Following is the implementation of this validate() function:

<script type="text/javascript">

<!--

// Form validation code will come here.

function validate()

{

 

   if( document.myForm.Name.value== "" )

   {

     alert( "Please provide your name!" );

     document.myForm.Name.focus() ;

     return false;

   }

   if( document.myForm.EMail.value== "" )

   {

     alert( "Please provide your Email!" );

     document.myForm.EMail.focus() ;

     return false;

   }

   if( document.myForm.Zip.value == "" ||

           isNaN(document.myForm.Zip.value ) ||

          document.myForm.Zip.value.length != 5 )

   {

     alert( "Please provide a zip in the format #####." );

     document.myForm.Zip.focus() ;

     return false;

   }

   if(document.myForm.Country.value == "-1" )

   {

     alert( "Please provide your country!" );

     return false;

   }

   return( true );

}

//-->

</script>

Data Format Validation:

Now we will see how we can validate our entered form data before submitting it to the web server.

This example shows how to validate an entered email address which means email address must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign:

<script type="text/javascript">

<!--

function validateEmail()

{

 

   var emailID =document.myForm.EMail.value;

   atpos = emailID.indexOf("@");

   dotpos =emailID.lastIndexOf(".");

   if (atpos < 1 || ( dotpos -atpos < 2 ))

   {

       alert("Please enter correct email ID")

      document.myForm.EMail.focus() ;

       return false;

   }

   return( true );

}

//-->

</script>

 

MySQL Connection

MySQL Connection

MySQL Connection using mysql binary:

You can establish MySQL database using mysqlbinary at command prompt.

Example:

Here is a simple example to connect to MySQL server from command prompt:

[root@host]# mysql -u root -p

Enter password:******

This will give you mysql> command prompt where you will be able to execute any SQL command. Following is the result of above command:

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 2854760 to server version: 5.0.9

 

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

In above example, we have used root as a user but you can use any other user. Any user will be able to perform all the SQL operations, which are allowed to that user.

You can disconnect from MySQL database any time using exit command at mysql> prompt.

mysql> exit

Bye

MySQL Connection using PHP Script:

PHP provides mysql_connect() function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success or FALSE on failure.

Syntax:

connectionmysql_connect(server,user,passwd,new_link,client_flag);

Parameter

Description

server

Optional - The host name running database server. If not specified, then default value is localhost:3036.

user

Optional - The username accessing the database. If not specified, then default is the name of the user that owns the server process.

passwd

Optional - The password of the user accessing the database. If not specified, then default is an empty password.

new_link

Optional - If a second call is made tomysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned.

client_flags

Optional - A combination of the following constants:

MYSQL_CLIENT_SSL - Use SSL encryption

MYSQL_CLIENT_COMPRESS - Use compression protocol

MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names

MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection

You can disconnect from MySQL database anytime using another PHP functionmysql_close(). This function takes a single parameter, which is a connection returned bymysql_connect() function.

Syntax:

bool mysql_close ( resource $link_identifier );

If a resource is not specified then last opened database is closed. This function returns true if it closes connection successfully otherwise it returns false.

Example:

Try out the following example to connect to a MySQL server:

<html>

<head>

<title>Connecting MySQL Server</title>

</head>

<body>

<?php

   $dbhost = 'localhost:3036';

   $dbuser = 'guest';

   $dbpass = 'guest123';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn )

   {

     die('Could not connect: ' .mysql_error());

   }

   echo 'Connected successfully';

   mysql_close($conn);

?>

</body>

</html>

 

JqueryUI Position

JqueryUI Position

In this chapter we shall see one of the utility methods of jqueryUi, the position() method. Aposition() method allows you to position an element with respect to another element or mouse event.

jQuery UI extends the .position() method from jQuery core in a way that lets you describe how you want to position an element the same way you would naturally describe it to another person. Instead of working with numbers and math, you work with meaningful words (such as left and right) and relationships.

Syntax

Following is the syntax of the position() method:

.position( options )

Where options is of type Object and provides the information that specifies how the elements of the wrapped set are to be positioned. Following table lists the different options that can be used with this method:

Option

Description

my

This option specifies the location of the wrapped elements (the ones being re-positioned) to align with the target element or location. By default its value is center.

at

This option is of type String and specifies the location of the target element against which to align the re-positioned elements. Takes the same values as the my option. By default its value is center.

of

This is of type Selector or Element or jQuery or Event. It identifies the target element against which the wrapped elements are to be re-positioned, or an Event instance containing mouse coordinates to use as the target location. By default its value is null.

collision

This option is of type String and specifies the rules to be applied when the positioned element extends beyond the window in any direction. By default its value is flip.

using

This option is a function that replaces the internal function that changes the element position. Called for each wrapped element with a single argument that consists of an object hash with the left and top properties set to the computed target position, and the element set as the function context. By default its value is null.

within

This option is a Selector or Element or jQuery element, and allows you to specify which element to use as the bounding box for collision detection. This can come in handy if you need to contain the positioned element within a specific section of your page. By default its value is window.

 

Example

Following example demontstrates the use ofposition method.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI position method Example</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <!-- CSS -->

      <style>

         .positionDiv {

            position: absolute;

            width: 75px;

            height: 75px;

            background: #b9cd6d;

         }

         #targetElement{

            width: 300px;

            height: 500px;

            padding-top:50px;

         }

      </style>

      <script>

         $(function() {

            // Position the dialogoffscreen to the left, but centered vertically

            $( "#position1" ).position({

               my: "center",

               at: "center",

               of: "#targetElement"

            });

            $( "#position2" ).position({

               my: "left top",

               at: "left top",

               of: "#targetElement"

            });

            $( "#position3" ).position({

               my: "right-10 top+10",

               at: "right top",

               of: "#targetElement"

            });

            $( document).mousemove(function( event ) {

               $( "#position4" ).position({

                  my: "left+3 bottom-3",

                  of: event,

                  collision: "fit"

               });

            });

         });

      </script>

   </head>

   <body>

      <div id="targetElement">

         <div class="positionDiv" id="position1">Box 1</div>

         <div class="positionDiv" id="position2">Box 2</div>

         <div class="positionDiv" id="position3">Box 3</div>

         <div class="positionDiv" id="position4">Box 4</div>

      </div>

   </body>

</html>

Let's save above code in an HTML filepositionmethodexample.htm and open it in a standard browser which supports javascript, you must see the following output. Now you can play with the result:

Box 1

Box 2

Box 3

Box 4

In this example we see that:

Box 1 is aligned to center (horizontally and vertically) of the div element.

Box 2is aligned to left top (horizontally and vertically) of the div element.

Box 3is displayed in the top right corner of the window, but leave some padding so that the message stands out more. This is done using the horizontal and vertical values of my or at.

For Box 4, the of value is set as an event object. This is an event associated with a pointer and moves with the mouse event.

 

JavaScript Operators

JavaScript Operators

What is an operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. JavaScript language supports following type of operators.

Arithmetic Operators

Comparision Operators

Logical (or Relational) Operators

Assignment Operators

Conditional (or ternary) Operators

Lets have a look on all operators one by one.

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator

Description

Example

+

Adds two operands

A + B will give 30

-

Subtracts second operand from the first

A - B will give -10

*

Multiply both operands

A * B will give 200

/

Divide numerator bydenumerator

B / A will give 2

%

Modulus Operator and remainder of after an integer division

B % A will give 0

++

Increment operator, increases integer value by one

A++ will give 11

--

Decrement operator, decreases integer value by one

A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".

The Comparison Operators:

There are following comparison operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator

Description

Example

==

Checks if the value of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!=

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>

 

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

<

 

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

The Logical Operators:

There are following logical operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator

Description

Example

&&

Called Logical AND operator. If both the operands are non zerothen then condition becomes true.

(A && B) is true.

||

Called Logical OR Operator. If any of the two operands are nonzero then then condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language

Assume variable A holds 2 and variable B holds 3 then:

Operator

Description

Example

&

Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments.

(A & B) is2 .

|

Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.

(A | B) is 3.

^

Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.

(A ^ B) is 1.

~

Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand.

(~B) is -4 .

<<

 

Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.

(A << 1) is 4.

>>

 

Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on.

(A >> 1) is 1.

>>>

 

Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,

(A >>> 1) is 1.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:

Operator

Description

Example

=

Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B willassignevalue of A + B into C

+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Miscellaneous Operator

The Conditional Operator (? :)

There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:

Operator

Description

Example

? :

Conditional Expression

If Condition is true ?Then value X : Otherwise value Y

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

Here is the list of return values for the typeofOperator :

Type

String Returned by typeof

Number

"number"

String

"string"

Boolean

"boolean"

Object

"object"

Function

"function"

Undefined

"undefined"

Null

"object"

 

JavaScript The Math Object

JavaScript The Math Object

The math object provides you properties and methods for mathematical constants and functions.

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static and can be called by using Math as an object without creating it.

Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument.

Syntax:

Here is the simple syntax to call properties and methods of Math.

var pi_val = Math.PI;

var sine_val = Math.sin(30);

Math Properties:

Here is a list of each property and their description.

Property

Description

E

Euler's constant and the base of natural logarithms, approximately 2.718.

LN2

Natural logarithm of 2, approximately 0.693.

LN10

Natural logarithm of 10, approximately 2.302.

LOG2E

Base 2 logarithm of E, approximately 1.442.

LOG10E

Base 10 logarithm of E, approximately 0.434.

PI

Ratio of the circumference of a circle to its diameter, approximately 3.14159.

SQRT1_2

Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

SQRT2

Square root of 2, approximately 1.414.

Math Methods

Here is a list of each method and its description.

Method

Description

abs()

Returns the absolute value of a number.

acos()

Returns the arccosine (in radians) of a number.

asin()

Returns the arcsine (in radians) of a number.

atan()

Returns the arctangent (in radians) of a number.

atan2()

Returns the arctangent of the quotient of its arguments.

ceil()

Returns the smallest integer greater than or equal to a number.

cos()

Returns the cosine of a number.

exp()

Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.

floor()

Returns the largest integer less than or equal to a number.

log()

Returns the natural logarithm (base E) of a number.

max()

Returns the largest of zero or more numbers.

min()

Returns the smallest of zero or more numbers.

pow()

Returns base to the exponent power, that is, base exponent.

random()

Returns a pseudo-random number between 0 and 1.

round()

Returns the value of a number rounded to the nearest integer.

sin()

Returns the sine of a number.

sqrt()

Returns the square root of a number.

tan()

Returns the tangent of a number.

toSource()

Returns the string "Math".

 

JqueryUI Environment Setup

JqueryUI Environment Setup

This chapter will discuss about download and set up of JqueryUI library. We will also briefly study the directory structure and its contents. JqueryUIlibrary can be used in two ways in your web page:

Downloading UI Library from its officialwebiste

Downloading UI Library from CDNs

Download UI Library from its official website

When you open the link http://jqueryui.com/, you will see there are three options to downloadJqueryUI library:

Custom Download - Click on this button to download a customized version of library.

Stable - Click on this button to get the stable and latest version of JqueryUIlibrary.

Legacy - Click on this button to get the previous major release of the JqueryUIlibrary.

Custom Download with Download Builder

Using Download Builder you can create a custom build including only the portions of the library that you need and download this new customized version of JqueryUI, depending on the chosen theme. You will see the screen as below (same page is split in two images):

This is useful for production usage when you would want to use only specific plugin or feature of the JqueryUI library. The directory structure of this version is as shown in following figure:

Uncompressed files are located in thedevelopment-bundle directory. The uncompressed file is best used during development or debugging; the compressed file saves bandwidth and improves performance in production.

Stable download

Click on the Stable button, which leads directly to a ZIP file containing the sources, examples, and documentation for latest version ofJqueryUI library. Extract the ZIP file contents to a jqueryui directory.

This version contains all files including all dependencies, a large collection of demos, and even the library’s unit test suite. This version is helpful to getting started.

Legacy download

Click on the Legacy button, which leads directly to a ZIP file of previous major release ofJqueryUI library. This version also contains all files including all dependencies, a large collection of demos, and even the library’s unit test suite. This version is helpful to getting started.

Download UI Library from CDNs

A CDN or Content Delivery Network is a network of servers designed to serve files to users. If you use a CDN link in your web page, it moves the responsibility of hosting files from your own servers to a series of external ones. This also offers an advantage that if the visitor to your webpage has already downloaded a copy ofJqueryUI from the same CDN, it won't have to be re-downloaded.

The jQuery FoundationGoogle, and Microsoftall provide CDNs that host jQuery core as well as jQuery UI.

Because a CDN does not require you to host your own version of jQuery and jQuery UI, it is perfect for demos and experimentation.

We are using the CDN versions of the library throughout this tutorial.

Example

Now let us write a simple example usingJqueryUI. Let us create an HTML file, copy the following content to the <head> tag:

<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

<scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

<scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

Details of above code are:

The first line, adds jQuery UI theme (in our case ui-lightness) via CSS. This CSS will make our UI stylish.

Second line, adds the jQuery library, as jQuery UI is built on top of jQuery library.

Third line, adds the jQuery UI library. This enables jQuery UI in your page.

Now let's add some content to <head> tag:

<script type="text/javascript">

   $(function () {

      $('#dialogMsg').dialog();

   });

</script>

In the <body> add this:

<body>

   <form id="form1" runat="server">

      <div id="dialogMsg" title="FirstJqueryUI Example">

         Hello this is my firstJqueryUI example.

      </div>

   </form>

</body>

The complete HTML code is as below. Save it asmyfirstexample.html

<!DOCTYPE html>

<head>

   <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

   <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

   <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

   <script type="text/javascript">

      $(function () {

         $('#dialogMsg').dialog();

      });

   </script>

</head>

<body>

   <form id="form1" runat="server">

      <div id="dialogMsg" title="FirstJqueryUI Example">

         Hello this is my firstJqueryUI example.

      </div>

   </form>

</body>

<html>

 

jQuery Basics

jQuery Basics

jQuery is a framework built using JavaScript capabilities. So you can use all the functions and other capabilities available in JavaScript.

This chapter would explain most basic concepts but frequently used in jQuery.

String:

A string in JavaScript is an immutable object that contains none, one or many characters.

Following are the valid examples of a JavaScript String:

"This is JavaScript String"

'This is JavaScript String'

'This is "really" a JavaScript String'

"This is 'really' a JavaScript String"

Numbers:

Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings.

Following are the valid examples of a JavaScript Numbers:

5350

120.27

0.26

Boolean:

A boolean in JavaScript can be either true orfalse. If a number is zero, it defaults to false. If an empty string defaults to false:

Following are the valid examples of a JavaScript Boolean:

true      // true

false     // false

0         // false

1         // true

""        // false

"hello"   // true

Objects:

JavaScript supports Object concept very well. You can create an object using the object literal as follows:

var emp = {

   name: "Zara",

   age: 10

};

You can write and read properties of an object using the dot notation as follows:

// Getting object properties

emp.name  // ==> Zara

emp.age   // ==> 10

 

// Setting object properties

emp.name = "Daisy"  // <== Daisy

emp.age  =  20      // <== 20

Arrays:

You can define arrays using the array literal as follows:

var x = [];

var y = [1, 2, 3, 4, 5];

An array has a length property that is useful for iteration:

var x = [1, 2, 3, 4, 5];

for (var i = 0; i < x.length; i++) {

   // Do something with x[i]

 }

Functions:

A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows:

function named(){

  // do some stuff here

}

An anonymous function can be defined in similar way as a normal function but it would not have any name.

A anonymous function can be assigned to a variable or passed to a method as shown below.

var handler = function (){

  // do some stuff here

}

JQuery makes a use of anonymous functions very frequently as follows:

$(document).ready(function(){

  // do some stuff here

});

Arguments:

JavaScript variable arguments is a kind of array which has length property. Following example explains it very well:

function func(x){

  console.log(typeof x,arguments.length);

}

func();                //==> "undefined", 0

func(1);               //==> "number", 1

func("1", "2", "3");   //==> "string", 3

The arguments object also has a callee property, which refers to the function you're inside of. For example:

function func() {

   return arguments.callee;

}

func();                // ==> func

Context:

JavaScript famous keyword this always refers to the current context. Within a function thiscontext can change, depending on how the function is called:

$(document).ready(function() {

  // this refers to window.document

});

 

$("div").click(function() {

  // this refers to a div DOM element

});

You can specify the context for a function call using the function-built-in methods call() andapply() methods.

The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments.

function scope() {

  console.log(this,arguments.length);

}

 

scope() // window, 0

scope.call("foobar", [1,2]);  //==> "foobar", 1

scope.apply("foobar", [1,2]); //==> "foobar", 2

Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.

Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name:

var myVar = "global";     // ==> Declare a global variable

 

function ( ) {

   var myVar = "local";   // ==> Declare a local variable

   document.write(myVar); // ==> local

}

Callback:

A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.

jQuery's event system uses such callbacks everywhere for example:

$("body").click(function(event) {

   console.log("clicked: " +event.target);

 });

Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event.

Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows:

$("#myform").submit(function() {

   return false;

 });

Closures:

Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.

Following example shows how the variablecounter is visible within the create, increment, and print functions, but not outside of them:

function create() {

  var counter = 0;

  return {

    increment: function() {

      counter++;

    },

    print: function() {

      console.log(counter);

    }

  }

}

var c = create();

c.increment();

c.print();     // ==> 1

This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming.

Proxy Pattern:

A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject.

A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows:

(function() {

  // log all calls to setArray

  var proxied = jQuery.fn.setArray;

 

  jQuery.fn.setArray = function() {

    console.log(this, arguments);

    return proxied.apply(this, arguments);

  };

})();

The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments)guarantees that the caller won't be able to notice the difference between the original and theproxied method.

Built-in Functions:

JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates.

Following are important JavaScript functions:

Method

Description

charAt()

Returns the character at the specified index.

concat()

Combines the text of two strings and returns a new string.

forEach()

Calls a function for each element in the array.

indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.

length()

Returns the length of the string.

pop()

Removes the last element from an array and returns that element.

push()

Adds one or more elements to the end of an array and returns the new length of the array.

reverse()

Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first.

sort()

Sorts the elements of an array.

substr()

Returns the characters in a string beginning at the specified location through the specified number of characters.

toLowerCase()

Returns the calling string value converted to lower case.

toString()

Returns the string representation of the number's value.

toUpperCase()

Returns the calling string value converted to uppercase.

A complete list of built-in function is availablehere : Built-in Functions.

The Document Object Model:

The Document Object Model is a tree structure of various elements of HTML as follows:

<html>

<head>

   <title>the title</title>

</head>

<body>

   <div>

      <p>This is a paragraph.</p>

      <p>This is second paragraph.</p>

      <p>This is third paragraph.</p>

   </div>

</body>

</html>

Following are the important points about the above tree structure:

The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>.

The <head> and <body> elements are not only descendants, but children of <html>, as well.

Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent.

The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements.

 

JqueryUI Tabs

JqueryUI Tabs

Tabs are sets of logically grouped content that allow us to quickly flip between them to. Tabs allow us to save space like accordions. For tabs to work properly following set of markups needs to used:

Tabs must be in a list either ordered(<ol>) or unordered(<ul>).

Each tab title must be within each <li> and wrapped by anchor (<a>) tag with an hrefattribute.

Each tab panel may be any valid element but it must have an id which corresponds to the hash in the anchor of the associated tab.

jQueryUI provides us tabs () method drastically changes the appearance of HTML elements inside the page. This method traverses (internally in jQuery UI) HTML code and adds new CSS classes to the elements concerned (here, the tabs) to give them the appropriate style.

Syntax

The tabs () method can be used in two forms:

$(selector, context).tabs (options) Method

$(selector, context).tabs ("action", params)Method

$(selector, context).tabs (options) Method

The tabs (options) method declares that an HTML element and its content should be managed as tabs. The options parameter is an object that specifies the appearance and behavior of tabs.

Syntax

$(selector, context).tabs (options);

You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows:

$(selector, context).tabs({option1: value1, option2: value2..... });

Following table lists the different options that can be used with this method:

Option

Description

active

This option specifies the current active tab/panel. By default its value is 0.

collapsible

This option set to true, it allows tabs to be deselected. When set to false (the default), clicking on a selected tab does not deselect (it remains selected). By default its value is false.

disabled

This option uses an array to indicate index tabs that are disabled (and therefore cannot be selected). For example, use [0, 1] to disable the first two tabs. By default its value is false.

event

This option is a name of the event that lets users select a new tab. If, for example, this option is set to "mouseover", passing the mouse over a tab will select it. By default its value is "click".

heightStyle

This option controls the height of the tabs widget and each panel. By default its value is "content".

hide

This option specifies how to animate hiding of panel. By default its value is null.

show

This option specifies how to animate showing of panel. By default its value is null.

Following section will show you few working examples of tabs functionality.

Default Functionality

The following example demonstrates a simple example of tabs functionality, passing no parameters to the tabs() method .

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-1" ).tabs();

         });

      </script>

      <style>

         #tabs-1{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

      </style>

   </head>

   <body>

      <div id="tabs-1">

         <ul>

            <li><a href="#tabs-2">Tab 1</a></li>

            <li><a href="#tabs-3">Tab 2</a></li>

            <li><a href="#tabs-4">Tab 3</a></li>

         </ul>

         <div id="tabs-2">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor sit

            amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-3">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

         <div id="tabs-4">

            <p>ed ut perspiciatis undeomnis iste natus error sit

            voluptatem accusantiumdoloremque laudantium, totam remaperiam,

            eaque ipsa quae ab illoinventore veritatis et quasiarchitecto

            beatae vitae dicta suntexplicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

      </div>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output. Now you can play with the result:

Try our system

In the above example click on tabs to swap between content.

Use of heightStyle, collapsible and hide

The following example demonstrates the usage of three options (a) heightStyle (b) collapsibleand (c) hide in the tabs function of JqueryUI.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-5" ).tabs({

               heightStyle:"fill",

               collapsible:true,

               hide:"slideUp"

            });

         });

      </script>

      <style>

         #tabs-5{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

      </style>

   </head>

   <body>

      <div id="tabs-5">

         <ul>

            <li><a href="#tabs-6">Tab 1</a></li>

            <li><a href="#tabs-7">Tab 2</a></li>

            <li><a href="#tabs-8">Tab 3</a></li>

         </ul>

         <div id="tabs-6">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor

            sit amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-7">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

               sed do eiusmod temporincididunt ut labore et dolore magna

               aliqua. Ut enim ad minim veniam, quis nostrudexercitation

               ullamco laboris nisi utaliquip ex ea commodo consequat. </p>

            </div>

         <div id="tabs-8">

            <p>ed ut perspiciatis undeomnis iste natus error sit voluptatem

            accusantium doloremquelaudantium, totam rem aperiam, eaqueipsa quae

            ab illo inventoreveritatis et quasi architecto beataevitae dicta

            sunt explicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

      </div>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output. Now you can play with the result:

Tab 1

Tab 2

Tab 3

Neque porro quisquam est qui dolorem ipsumquia dolor sit amet, consectetur, adipisci velit...

Click the selected tab to toggle its content closed/open. You can also see the animation effect "slideUp" when the tab is closed.

Use of event

The following example demonstrates the usage of three options event in the tabs function ofJqueryUI.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-9" ).tabs({

               event:"mouseover"

            });

         });

      </script>

      <style>

         #tabs-9{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

      </style>

   </head>

   <body>

      <div id="tabs-9">

         <ul>

            <li><a href="#tabs-10">Tab 1</a></li>

            <li><a href="#tabs-11">Tab 2</a></li>

            <li><a href="#tabs-12">Tab 3</a></li>

         </ul>

         <div id="tabs-10">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor

            sit amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-11">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

         <div id="tabs-12">

            <p>ed ut perspiciatis undeomnis iste natus error sit

            voluptatem accusantiumdoloremque laudantium, totam remaperiam,

            eaque ipsa quae ab illoinventore veritatis et quasiarchitecto

            beatae vitae dicta suntexplicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

      </div>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output. Now you can play with the result:

Try Our System

In the above example toggle the sections open/closed with mouseover the tabs.

$(selector, context).tabs ("action", params) Method

The tabs ("action", params) method allows an action on the tabs (through a JavaScript program), selecting, disabling, adding, or removing a tab. The action is specified as a string in the first argument (e.g., "add" to add a new tab). Check out the actions that can be passed, in the following table.

Syntax

$(selector, context).tabs ("action",params);;

Following table lists the different actions that can be used with this method:

Action

Description

destroy

This action destroys the tabs functionality of an element completely. The elements return to their pre-init state. This method does not accept any arguments.

disable

This action disables all tabs. This method does not accept any arguments.

disable( index )

This action disables the specified tab. Where index is the tab to be disabled.

enable

This action activates all the tabs. This signature does not accept any arguments.

enable( index )

This action activates a specified tab. Where index is the tab to be enabled.

load( index )

This action forces a reload of the indexed tab, ignoring the cache. Where index is the tab to load.

option(optionName )

This action gets the value currently associated with the specified optionName.

option

This action gets an object containing key/value pairs representing the current tabs options hash.

option(optionName, value )

This action sets the value of the tabs option associated with the specified optionName. The argument optionName is name of the option to be set and valueis the value to be set for the option.

option( options )

This action sets one or more options to the tabs.

refresh

This action recomputes the height of the tab panels when any tabs that were added or removed directly in the DOM. Results depend on the content and the heightStyle option.

widget

This action returns the element serving as the tabs widget, annotated with the ui-tabs class name.

 

Use of action disable()

Now let us see an example using the actions from the above table. The following example demonstrates the use of disable() method.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-13" ).tabs();

            $( "#tabs-13" ).tabs("disable");

         });

      </script>

      <style>

         #tabs-13{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

      </style>

   </head>

   <body>

      <div id="tabs-13">

         <ul>

            <li><a href="#tabs-14">Tab 1</a></li>

            <li><a href="#tabs-15">Tab 2</a></li>

            <li><a href="#tabs-16">Tab 3</a></li>

         </ul>

         <div id="tabs-14">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor

            sit amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-15">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamco

            laboris nisi ut aliquip exea commodo consequat. </p>

         </div>

         <div id="tabs-16">

            <p>ed ut perspiciatis undeomnis iste natus error sit

            voluptatem accusantiumdoloremque laudantium, totam remaperiam,

            eaque ipsa quae ab illoinventore veritatis et quasiarchitecto

            beatae vitae dicta suntexplicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

      </div>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output:

Try Our System

Here you can see all the tabs are disabled.

Use of action disable(index)

Now let us see an example using the actions from the above table. The following example demonstrates the use of disable(index) method.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-17" ).tabs();

            $( "#tabs-17" ).tabs("disable",2);

         });

      </script>

      <style>

         #tabs-17{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

      </style>

   </head>

   <body>

      <div id="tabs-17">

         <ul>

            <li><a href="#tabs-18">Tab 1</a></li>

            <li><a href="#tabs-19">Tab 2</a></li>

            <li><a href="#tabs-20">Tab 3</a></li>

         </ul>

         <div id="tabs-18">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor

            sit amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-19">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>

         </div>

         <div id="tabs-20">

            <p>ed ut perspiciatis undeomnis iste natus error sit voluptatem

            accusantium doloremquelaudantium, totam rem aperiam, eaqueipsa quae

            ab illo inventoreveritatis et quasi architecto beataevitae dicta

            sunt explicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris nisi

            ut aliquip ex ea commodoconsequat. </p>

         </div>

      </div>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output:

Try Our System

In the above example you notice that Tab 3 is disabled.

Event Management on tabs elements

In addition to the tabs (options) method we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below:

Event Method

Description

activate(event, ui)

This event is triggered after the tab has been activated (after the completion of animation).

beforeActivate(event,ui)

This event is triggered before a the tab has been activated.

beforeLoad(event, ui)

This event is triggered when a remote tab is about to be loaded, after the beforeActivate event. This event is triggered just before the Ajax request is made.

create(event, ui)

This event is triggered when tabs are created.

load(event, ui)

This event is triggered after a remote tab has been loaded.

Example

The following example demonstrates the event method usage in tabs widgets. This example demonstrates the use of events activate andcreate.

<!doctype html>

<html lang="en">

   <head>

      <meta charset="utf-8">

      <title>jQuery UI Tabs functionality</title>

      <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"rel="stylesheet">

      <scriptsrc="http://code.jquery.com/jquery-1.10.2.js"></script>

      <scriptsrc="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <script>

         $(function() {

            $( "#tabs-21" ).tabs({

               activate: function( event, ui ) {

                  var result = $( "#result-2" ).empty();

                  result.append("activated" );

               },

               create: function( event, ui ) {

                  var result = $( "#result-1" ).empty();

                  result.append("created" );

               }

            });

         });

      </script>

      <style>

         #tabs-21{font-size: 14px;}

         .ui-widget-header {

            background:#b9cd6d;

            border: 1px solid #b9cd6d;

            color: #FFFFFF;

            font-weight: bold;

         }

         .resultarea {

            background: #cedc98;

            border-top: 1px solid #000000;

            border-bottom: 1px solid #000000;

            color: #333333;

            font-size:14px;

         }

      </style>

   </head>

   <body>

      <div id="tabs-21">

         <ul>

            <li><a href="#tabs-22">Tab 1</a></li>

            <li><a href="#tabs-23">Tab 2</a></li>

            <li><a href="#tabs-24">Tab 3</a></li>

         </ul>

         <div id="tabs-22">

            <p>Neque porro quisquamest qui dolorem ipsum quia dolor

            sit amet, consectetur,adipisci velit... </p>

         </div>

         <div id="tabs-23">

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua.

            Ut enim ad minim veniam,quis nostrud exercitation ullamcolaboris

            nisi ut aliquip ex eacommodo consequat. </p>  

         </div>

         <div id="tabs-24">

            <p>ed ut perspiciatis undeomnis iste natus error sit voluptatem

            accusantium doloremquelaudantium, totam rem aperiam, eaqueipsa quae

            ab illo inventoreveritatis et quasi architecto beataevitae dicta

            sunt explicabo.  </p>

            <p>Lorem ipsum dolor sitamet, consectetur adipisicing elit,

            sed do eiusmod temporincididunt ut labore et dolore magnaaliqua. Ut

            enim ad minim veniam, quisnostrud exercitation ullamco laborisnisi

            ut aliquip ex ea commodoconsequat. </p>

         </div>

      </div><br>

      <span class="resultarea" id=result-1></span><br>

      <span class="resultarea" id=result-2></span>

   </body>

</html>

Let's save above code in an HTML filetabsexample.htm and open it in a standard browser which supports javascript, you must see the following output:

Try Our System

created

Click on the tabs to see a message getting printed below on specific to events.