Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, 15 May 2012

jQuery Effects And Animation


The jQuery library provides several techniques for adding animation to a web page.
These include simple, standard animations that are frequently used, and the ability to craft sophisticated custom effects.

.hide() Hide the matched elements.
$('#book').hide();
.show() Display the matched elements.
$('#book').show();
$('#clickme').click(function() {
                 $('#book').show('slow', function() {
                                 // Animation complete.
                });
});

.fadeIn() .fadeOut() Display the matched elements by fading them to opaque and back respectively.
$("div").fadeIn(“slow”);
$("div").fadeIn(3000, function () { 
});

.toggle() Display or hide the matched elements.
<p>Hello</p> 
$("p").toggle(); 
$("p").toggle("slow"); 

jQuery Event Handling

Jquery provides methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.



.bind() Attach a handler to an event for the elements.


<input type=“button” id=“myButton” value=“GO”/>
$(‘#myButton').bind('click', function() {
                alert('User clicked on "foo."');
});


Bind Multiple Events
$(‘#myButton').bind('mouseenter mouseleave', function() {
                alert(‘Action Performed');
});


.unbind() Remove a previously-attached event handler from the elements.
$(‘#myButton').unbind('click');

Events


event.preventDefault() If this method is called, the default action of the event will not be triggered.
<a href="http://jquery.com">jquery home page</a> 
$("a").click(function(event) {   
                event.preventDefault(); 
                alert(“default prevented”);
});


.trigger() Execute all handlers and behaviors attached to the matched elements for the given event type.
$('#myButton').bind('click', function() {
                alert($(this).text());
});
$('#myButton').trigger('click');

.live() Attach a handler to the event for all elements which match the current selector, now and in the future.
<span class=“clickme”> CLICK ME</span>
$('.clickme').live('click', function() {
                 // Live handler called.
});
$('body').append('<div class="clickme">Another target</div>');


.die() Remove all event handlers previously attached using .live() from the elements.
$('.clickme').die('click‘);

Few event methods available in jquery
.blur()
.change()
.click()
.dblclick()
.keydown()
.keypress()
.keyup()
.mousedown()
.mouseenter()
.mousemove()
.mouseout()
.mouseover()
.mouseup()

Usage:
$('#myButton').dblclick(function() {
                alert('Handler for .mousedown() called.');
});

jQuery DOM Manipulation

.html() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").html();  //Output <b>Demonstration Box</b>

.text() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").text();  //Output Demonstration Box

.val() Get the current value of the first element in the set of matched elements
Ex: <input type=“text” id=“uname” value=“Johnny”/>

$(“uname").val();  //Output Johnny

.append() Insert content, specified by the parameter, to the end of each element in the set of matched elements.

<p>I would like to say: </p>

<script>$("p").append("<strong>Hello</strong>");</script>

Output : <p>I would like to say: <strong>Hello</strong></p>

.prepend() Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

<p>I would like to say: </p>
<script>$("p").prepend("<strong>Hello</strong>");</script>
Output : <p><strong>Hello</strong> I would like to say:</p>

<div>
                <span>One</span>
                <p>Two</p>
                <span>Three</span>
</div>
.remove() Remove the set of matched elements from the DOM.
$(“div”).remove(“p”);
Output:
<div>
                <span>One</span>
                <span>Three</span>
</div>
.empty() Remove all child nodes of the set of matched elements from the DOM.
$(“div”).empty();
<div>
</div>

<input type=“text” id=“mydata” style=“font-size:10px;”/>

.attr() Get or Set the value of an attribute for the first element in the set of matched elements.
$(“#mydata”).attr(“style”)  // Output : font-size:10px;
$(“#mydata”).attr(“name”,”mynode”) 
// Output : <input type=“text” id=“mydata” name=“mynode” style=“font-size:10px;”/>


 .removeAttr() Remove an attribute from each element in the set of matched elements.
$(“#mydata”).removeAttr(“style”)
//Output : <input type=“text” id=“mydata” />

Dom nodes can be created in Jquery using the $ or jquery()
$(“<div>This is a div element</div>”)
$(“<input></input>”).attr(“type”,”text”).attr(“name”,”mydata”)
The above is equivalent to <input type=“text” name=“mydata”/>
$(“<span><b>Hello world</b></span>”)

jQuery DOM Traversal

.filter()
Reduce the set of matched elements to those that match the selector or pass the function's test.
Ex:
<div></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div></div>


$("div").filter(".middle“).css("border-color", "red");


. siblings()
Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
Ex:
<div>
                <span class=“oldStyle”></span>
                <a></a>
                <ul class=“oldStyle”></ul>
</div>


$("div”). siblings(“.oldStyle“).css("border-color", "red");



jQuery Selectors

jQuery offers a powerful set of tools for matching a set of elements in a document

Element Selector
Notation:$(“element”)                    
Ex : To select all input types use $(“input”)
<input type=“text”  id=“userame” name=“username” value=“rayudu”/>
<input type=“text”  id=“age” name=“age” value=“29”/>
<input type=“text” id=“dob” name=“dob” value=“18-09-1978”/>


ID Selector
Notation:$(“#id”)
Ex : To select element with id dob use $(“#dob”)
<input type=“text”  id=“userame” name=“username” value=“rayudu”/>
<input type=“text”  id=“age” name=“age” value=“29”/>
<input type=“text” id=“dob” name=“dob” value=“18-09-1978”/>

Class Selector
To select all elements using CSS class
Notation:$(“.classname”) 
Ex: $(“.customStyle”)
<input type=“text” class=“customStyle”  id=“userame” name=“username”/>
<div class=“newStyle”  id=“display1”></div>
<div class=“customStyle”  id=“display2”></div>
<span class=“customStyle”  id=“display3”></span>

Ancestor Descendant
Selects all elements that are descendants of a given ancestor.
Notation:$(“E F”) 
Ex : $(“div input”)
             <div>
                  <input type=“text” name=“username”/>
                 <span>
                    <input type=“text” name=“rollno”/>
                 </span>
             </div>
                <input type=“text” name=“rollno”/>

:first-child, :last:child, :only-child :nth-child(n)
$(“li:first-child”);
$(“tr:last-child”);
$(“img:only-child”);
$(“tr:nth-child(2n)”);

Attribute Selectors
Has Attribute: $(“img[alt]”);
Begins With: $(“input[name^=my]”);
Ends With: $(“a[href$=.pdf]”);
Contains: $(“a[href*=microsoft]”);
Equals: $(“:checkbox[checked=true]”)
:not(s), :empty, :eq(n), :contains(s)

jQuery Overview


jQuery is a lightweight, open-source JavaScript library (framework) that simplifies interaction between HTML and JavaScript which makes the developer’s life easier

jQuery Notation
jQuery() = $()
·         Represented by both $ and jQuery
·         Use $.noConflict() (-for jQuery only), for other frameworks that use $
·         By default, represents the jQuery object. When combined with a selector, can represent multiple DOM Elements.
·         Used with all jQuery functions.

jQuery Setup
·         Step 1 : Download Jquery from http://code.jquery.com/jquery-1.5.1.min.js
·         Step 2 : Place the the downloaded jquery-1.5.2.min.js in the same folder which contains the HTML files
·         Step 3 : Include the jquery-1.5.2.min.js in the HTML code
<html>
<head>
                <script src=“jquery-1.5.2.min.js "></script>
</head>
<body>
                some content…..
</body>
</html>

$(document).ready
Function to execute when the DOM is fully loaded.
$(document).ready(function() {
                 // Handler for .ready() called.
});
Best place to attach all other event handlers and run other jQuery code

Friday, 4 May 2012

JavaScript Regular Expression

A regular expression is really just a sequence of characters that specify a pattern to be matched against a string of text when performing searches and replacements. A simple regular expression consists of a character or set of characters that matches itself.

JavaScript regular expressions are used primarily to verify data input on the client side.

Checking the form on the client side allows for instant feedback, and less traveling back and forth between the browser and server. The ability to check for any type of input, such as e-mail addresses, passwords, Social Security numbers, and birthdates is greatly simplified.

The Constructor Method

The constructor method, called RegExp(), creates a RegExp object. The RegExp() constructor
takes one or two arguments. The first argument is the regular expression; it is a
string representing the regular expression, for example, “blue” represents the literal
regular expression /blue/. The second optional argument is called a flag such as i for
case insensitivity or g for global. The constructor method is used when the regular
expression is being provided from some other place, such as from user input, and can
change throughout the run of the program. This method is handled at runtime.

Options Used for Modifying Search Patterns

Option Purpose
i              Used to ignore case.
g             Used to match for all occurrences of the pattern in the string.
m            Used to match over multiple lines.
FORM
Syntax
var variablename = /regular expression/options;

Example
var myregexp = /freedom/;
var reobjexp = /Samuel/ig;

Syntax
var variablename = new RegExp("regular expression", "options");

Example
var myreg = new RegExp("Freedom");
var reobj = new RegExp("Samuel", "ig");

RegExp Object
The RegExp object has two methods that can be used to test for a match in a string,
the test() method and the exec() method, which are quite similar.

test() Method Tests for a match in a string and returns either true or false.

Example
var string="String to be tested comes here ";
var regex = /regular expression/; // Literal way
var regex=new RegExp("regular expression"); // Constructor way
regex.test(string); // Returns either true or false

or
/regular expression/.test("string");

FORMAT
exec() Method Executes a search for a match in a string and returns an array.

Example
array = regularexpression.exec(string);
or
list = /ring/.exec("This is a test string collection");

Tuesday, 24 April 2012

JavaScript Event Handlers


Event Handlers is one of the most important features of JavaScript. I came across a situation where I need to attach even to controls dynamically using JavaScript. So Event Handler helped me to finish of the task.  Different methods can be invoked from the same event handler and we can remove it whenever it is not necessary.

Types of Event Handlers as follows,

The addEventListener() Method
It actually allow you to specify a function to be executed for the event

Syntax: 
element.addEventListener('event_type', function_name, true_or_false);

Sample Eg:
var mypage= "http://www.ajaal.com";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.addEventListener('click', function() { window.location = mypage;
}, false);

The removeEventListener()  Method
To remove an event whenever we don’t need we can use the removeEventListener() method.

Syntax:
element.removeEventListener('event_type', function_name, 
true_or_false);

The attachEvent() Method
The attachEvent() method works in a similar way to addEventListener(). However, it only
works with event bubbling.

Syntax
element.attachEvent(event_handler, function_name);

Sample Eg:
var mypage = " http://www.ajaal.com ";
var varCtrl = document.getElementById("btnRedirect");
varCtrl.attachEvent(onclick, function() { window.location = mypage; } );

Notice that this method does use the name of the event handler (onclick). Also, it does not
have the third option; it just uses event bubbling.

The detachEvent() Method
To remove an event, you would use the detachEvent() method:

Syntax
element.detachEvent(event_handler, function_name)

Please comment your suggestion on this post for further improvement.

Monday, 23 April 2012

Javascript Exception Handling

Exception Handling is one of the most important and essential while programming in JavaScript.  If the exception is not handled properly then we may end up in exclamatory mark that will appear in the left bottom corner of the page. This is due to some exception or error that is available in the executed page. These JavaScript is a client side script so execution failure occur only in the browser from the client end and not in server

There are two ways of handling exception.


1.  Placing the code between the try and catch block. It is the most the easiest approach for error such as “Object not Found” exception/error.
Eg:
try
{
//JavaScript Code
}
catch (e)
{
}
Code:
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
try{
var servervalue = "two";
for(var i=0; i<document.getElementById("ItemLists").options.length; i++) {  
if ( document.getElementById("ItemLists").options[i].text == servervalue )
{   
  document.getElementById("ItemLists").selectedIndex = i;       break;
}
}
}
catch(e){ alert('Control Not Found!!!');}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>


2.  Another option is using null check, check to see a control available in the rendered page in the browser.
Eg:  If(Document.all("ItemLists") != null)


Code: 
<HTML>
<HEAD>
<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
var servervalue = "two";
//null check to see the control "ItemLists" available     in the html page
if (document.getElementById("ItemLists")!=null){
for(var i=0;  i<document.getElementById("ItemLists").options.length; i++)
{  
if (document.getElementById("ItemLists").options[i].text == servervalue )
 {   
  document.getElementById("ItemLists").selectedIndex = i;    
  break;  
 }
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<P>
Sample Dropdownlist
<SELECT NAME="ItemList" onchange="Javascript:getValue();">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>

Sunday, 22 April 2012

Excel Pivot Table

Excel Pivot table is so useful for analyzing the data mostly for finding number occurrence of a data, summing of values of data for a range, etc. Please perform the below steps in Excel 2007 to see the sample.


1.       Select the data series as in the below screen shot

2.       Click on insert tab from the top menu as in the below screen shot

3.       Click on pivot table sub menu from pivot table from menu as in the below screen shot
3.       Click on Existing Worksheet and click OK as in the below screen shot


4.       The three columns appear in the right side Pivot table field list. 


5.       Drag and Drop the necessary columns to appear in the right side bottom columns. Finally see the result in the left side excel sheet.


Saturday, 21 April 2012

Javascript Debugging

There may be situation where you may need to debug the javascript code. Mostly you need to identify any of the following

  1. Strange error by showing "!" mark in the bottom right corner of the browser especially in IE.
  2. Value assigned to a variable or a control
  3. Html control present in the webpage
  4. Conditional Check etc.,
Use the syntax debugger; inside a Javascript method and In IE goto Tools -> Internet Options -> Advance tab -> uncheck both Disable script debugging (Internet Explorer) and Disable script debugging (Others) to debug the Javascript method.

Please refer below sample code which I am reusing the earlier version of code.

<HTML>
<HEAD>

<TITLE>Javascript Eg.</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function getValue() {
//In your case use the server tag here in place of "two" to //retrieve the saved value it vary from one server to other //server

//debugger the browser will start debugging from here
debugger;
var servervalue = "two";
for(var i=0; i<document.getElementById("ItemList").options.length; i++)
{
if ( document.getElementById("ItemList").options[i].text == servervalue )
 {  
  document.getElementById("ItemList").selectedIndex = i;  
  break;
 }
}
}
//Method 1.
//window.onload = getValue;
</SCRIPT>
</HEAD>
<!--Method 2.-->
<BODY onload="Javascript:getValue();">
<P>
Sample Dropdownlist
<SELECT NAME="ItemList">
<OPTION VALUE="one">one
<OPTION VALUE="two">two
<OPTION VALUE="three">three
<OPTION VALUE="four">four
</SELECT></P>
</BODY>
</HTML>




Javascript Simple Meu

There are some situations where developers need to create our custom html JavaScript menu without help of Web designers. So the below code will help in creating a Custom html JavaScript menu. So Please follow the below step to see the menu
  1. Save the CSS  code for Menu Code as Menu.css
  2. Save the JavaScript code  for Menu Code as Menu.js
  3. Save the html code  for Menu Code as Menu.htm
  4. Place all the three files in the same folder

/**********************  1. Menu.css *************************/

.ParentMenu
{
border-right: black 1px solid;
border-top: black 1px solid;
font-weight: lighter;
font-size: 10pt;
left: 10px;
text-transform: uppercase;
border-left: black 1px solid;
width: 100%;
color: teal;
border-bottom: black 1px solid;
font-style: normal;
font-family: verdana;
letter-spacing: 2pt;
position: absolute;
top: 100px;
height: 30px;
background-color: lightyellow;
text-align: center;
cursor: hand;
}
.ChildMenu
{
border-right: black 1px solid;
padding-right: 3px;
display: none;
padding-left: 3px;
font-weight: lighter;
font-size: 10pt;
padding-bottom: 2px;
text-transform: uppercase;
border-left: black 1px solid;
width: 20%;
color: teal;
padding-top: 2px;
border-bottom: black 1px solid;
font-style: normal;
font-family: verdana;
letter-spacing: 2pt;
position: absolute;
top: 129px;
height: 30px;
background-color: lightyellow;
text-align: left;
cursor: hand;
text-decoration: none;
}
A:link
{
    text-decoration: none;
    color:teal;
}
A:visited
{
    text-decoration: none;
    color:blue;
}
A:hover
{
    text-decoration: none;
    color:red;
}
A:active
{
    text-decoration: none;
    color:teal;
}
/**********************  2. Menu.js *************************/

<!--
function showMenu(subMenu)
{
document.all(subMenu).style.display='block';
}
function hideMenu(subMenu)
{
document.all(subMenu).style.display='none';
}
//-->


/**********************  3. Menu.htm *************************/

<html>
<head>
<title>Menu</title>
<LINK href="Menu.css" rel="stylesheet" type="text/css">
<script language="javascript" src="Menu.js" type="text/javascript"></script>
</head>


<body>
<table class="ParentMenu" id="PrtTable" cellpadding="0" cellspacing="0" border="0" align="center">
<tr>
<td onmouseover="showMenu('HomeTable')"  onmouseout="hideMenu('HomeTable')" style="WIDTH: 189px; CURSOR: hand">Home</td>
<td onmouseover="showMenu('PubTable')" onmouseout="hideMenu('PubTable')" style="WIDTH: 211px;CURSOR: hand">Publishers</td>
<td onmouseover="showMenu('ForumTable')" onmouseout="hideMenu('ForumTable')" style="WIDTH: 237px;CURSOR: hand">Forum</td>
<td onmouseover="showMenu('SearchTable')" onmouseout="hideMenu('SearchTable')" style="WIDTH: 156px;CURSOR: hand">Search</td>
<td onmouseover="showMenu('HelpTable')" onmouseout="hideMenu('HelpTable')" style="CURSOR: hand">Help</td>
</tr>
</table>


<table class="ChildMenu" id="HomeTable" onmouseover="showMenu('HomeTable')" onmouseout="hideMenu('HomeTable')"
cellpadding="5" cellspacing="2" border="0" style="LEFT: 10px;" align="center">
<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="">Publishers</a></td>
</tr>
<tr>
<td><a href="">Forum</a></td>
</tr>
<tr>
<td><a href="">Search</a></td>
</tr>
<tr>
<td><a href="">Help</a></td>
</tr>
</table>


<table class="ChildMenu" id="PubTable" onmouseover="showMenu('PubTable')" onmouseout="hideMenu('PubTable')"
cellpadding="5" cellspacing="2" border="0" style="LEFT: 200px;" align="center">
<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="">Publishers</a></td>
</tr>
<tr>
<td><a href="">Forum</a></td>
</tr>
<tr>
<td><a href="">Search</a></td>
</tr>
<tr>
<td><a href="">Help</a></td>
</tr>
</table>


<table class="ChildMenu" id="ForumTable" onmouseover="showMenu('ForumTable')" onmouseout="hideMenu('ForumTable')"
cellpadding="5" cellspacing="2" border="0" style="LEFT: 440px;" align="center">
<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="">Publishers</a></td>
</tr>
<tr>
<td><a href="">Forum</a></td>
</tr>
<tr>
<td><a href="">Search</a></td>
</tr>
<tr>
<td><a href="">Help</a></td>
</tr>
</table>


<table class="ChildMenu" id="SearchTable" onmouseover="showMenu('SearchTable')" onmouseout="hideMenu('SearchTable')"
cellpadding="5" cellspacing="2" border="0" style="LEFT: 650px;" align="center">
<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="">Publishers</a></td>
</tr>
<tr>
<td><a href="">Forum</a></td>
</tr>
<tr>
<td><a href="">Search</a></td>
</tr>
<tr>
<td><a href="">Help</a></td>
</tr>
</table>


<table class="ChildMenu" id="HelpTable" onmouseover="showMenu('HelpTable')" onmouseout="hideMenu('HelpTable')"
cellpadding="5" cellspacing="2" border="0" style="LEFT: 788px;" align="center">
<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="">Publishers</a></td>
</tr>
<tr>
<td><a href="">Forum</a></td>
</tr>
<tr>
<td><a href="">Search</a></td>
</tr>
<tr>
<td><a href="">Help</a></td>
</tr>
</table>
</body>
</html>