Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday 30 September 2014

How to close the popup window by pressing escape key button or clicking outside of the popup window with jQuery.

For closing the open popup window on the click of escape key or clciking outside the popup window, We need to create one jQuery method in every modal panel .xhtml file or any other .xhtml file which is used to show the popup window as:

<script type="text/javascript">
    jQuery(document).keyup(function (e){
            var clickedID = e.target.id;
            var unicode=e.keyCode? e.keyCode : e.charCode /*This will capture the key pressed event*/
                 if(unicode==27){//Key code for escape key is 27
                 Richfaces.hideModalPanel(#{modalPanelId});
                /*var win = window.open("","_self"); r
                 win.close();*/
                }
</script>


The above method will automatically be called whenever we press any key and if pressed key is escape key then it would close the opened popup window so it will work when we press theescape key.

To close popup window when we click on the outside of the popup window, we have to call “Richfaces. hideModalPanel(‘modelPanel Id’)” on “onmaskclick”  event of rich:modalPanel as:

onmaskclick="Richfaces.hideModalPanel('#{modalPanelId}')"

Friday 5 April 2013

Basics of JavaScript




Basic Syntax of JavaScript
The essential syntax need to write in the form to implement java script code

<script type="text/javascript">

// Your code here

</script>


Comment Types in JavaScript

  • Single line :- ( // ) indicates that the rest of the current line is a comment
  • Multiline :- ( /* ) indicatesp the beginning of a comment that covers more than one line and end with  (*/)

Important Summary

  • A semicolon or a newline defines the end of a statement, and a statement is a single command.
  • Semicolons are in fact optional, but it’s still a good idea to use them to make clear where statements end, because doing so makes your code easier to read and debug.
  • Curly braces ({ and }) are used to indicate a block of code. They ensure that all the lines inside the braces are treated as one block.

  • Java script code in script tag is executed in sequence and it is visible to users also

  • We can check the width and resoluon of computer screen as “screen.availWidth

  • Q - Diff bw prompt and alert in javascript??
     Ans - prompt is type of alert use to get the data from user
     prompt(‘What is your name’); and document.write is used to write something     
     on output stream

Datatypes in JavaScript

The three most basic data types that store data in JavaScript are

String: A series of characters, for example, “some characters
Everything written in ‘’ or “” is treated as string in javascript. The only difference is that’’ single quotes will always work except if the string itself has ‘ single quote init like “paul’s cow”

Number: A number, including floating point numbers
Javascript automatically change the data types like var a = 1+2; result is 3 means it treated it as number. Although we have Nunber(), parseInt and parseFloat to convert the string to integer and float resp. It also has one function as typeof which tells the datatype of a variable

The isNaN() function determines whether a value is an illegal number (Not-a-Number).This function returns true if the value is NaN, and false if not.

Boolean: Can contain a true or false value

There are two other important datatypes as

Null: Indicates that there is no data.
Undefined: Indicates that something has not been defined and given a value. This  
   is important when you’re working with variables


Operator What It Does in JavaScript
+             Adds two numbers together or concatenates two strings.
-              Subtracts the second number from the first.
*             Multiplies two numbers.
/              Divides the first number by the second.
%            Finds the modulus—the reminder of a division. For example, 98 % 10 = 8.
--             Decreases the number by 1: only useful with variables, which we’ll see at work later.
++           Increases the number by 1: only useful with variables, which we’ll see at work later.

Some Important Escape Sequences Character Represented in JavaScript
\b           Backspace.
\f            Form feed.
\n           Newline.
\r            Carriage return.
\t            Tab.
\'             Single quote.
\"            Double quote.
\\            Backslash.
\xNN     NN is a hexadecimal number that identifies a character in the Latin-1
character set (the Latin-1 character is the norm for English-speaking
countries).
\uDDDD DDDD is a hexadecimal number identifying a Unicode character.



Composite data types  are
1.       Object
                                                        I.      String
  String object have many other method like “indexOf”, “substring” etc
                                                      II.      Math
                                                    III.      Date
Date is not a primitive datatype in JS as in java, We have to create the object by new oprator for data as
var dt = new Date();
it has many function as getDate, getFullYear etc
JS counting month starting from 0(Janaury)
2.       Array
Var ar = new Array(3);   OR  var ar = new Array
(“de”,”ff”,”fg”);


Er.join(‘,’);  it will convert all element of ar array into string by adding comma in between all the elements
Split (‘, ’);    this is opposite to join
We can sort and reverse the array as ar.sort() and ar.reverse()

All operators have an order of precedence. Multiplication, division, and modulus have
equal precedence, so where they all appear in an equation the sum will be calculated from left
to right. Try this calculation:
2 * 10 / 5%3
The result is 1, because the calculation simply reads from left to right:
2 * 10 = 20
20 / 5 = 4
4%3 = 1

Addition and subtraction also have equal precedence.


Two ways to create  a string object are:
var myStringObject =  "abc" ;        //Implicit
 var myStringObject = new String( "abc" );  //Ecplicit
The result of checking the length property is the same whether we create the String
object implicitly or explicitly. The only real difference between creating String objects
explicitly or implicitly is that creating them explicitly is marginally more efficient if you’re
going to be using the same String object again and again. Explicitly creating String objects
also helps prevent the JavaScript interpreter getting confused between numbers and strings,
as it can do.


But for Date in JS we have only explicit way like
var todaysDate = new Date();



The Math object provides us with lots of mathematical functionality, like finding the square of a
number or producing a random number. The Math object is different from the Date and String
objects in two ways:
• You can’t create a Math object explicitly, you just go ahead and use it.
• The Math object doesn’t store data, unlike the String and Date object.

round(): Rounds a number up when the decimal is . 5 or greater
ceil() (as in ceiling): Always rounds up, so 23.75 becomes 24, as does 23.25
floor(): Always rounds down, so 23.75 becomes 23, as does 23.25



Array in JavaScript:

Array objects, like String and Date objects, are created using the new keyword together
with the constructor. We can initialize an Array object when we create it:
var preInitArray = new Array( "First item", "Second item",
"Third Item" );

Using index numbers to store items is useful if you want to loop through the array—we’ll
be looking at loops next.
You can use keywords to access the array elements instead of a numerical index, like this:

var anArray = new Array( );
var itemIndex = 0;
var itemKeyword = "CostOfApple";
anArray[itemIndex] = "Fruit";
anArray[itemKeyword] = 0.75;

The slice() method takes two parameters: the index of the first element of the slice, which
will be included in the slice, and the index of the final element, which won’t be. To access the
second, third, and fourth values from an array holding five values in all, we use the indexes 1

The Array object’s concat() method allows us to concatenate arrays. We can add two or more
arrays using this method, each new array starting where the previous one ends. Here we’re
joining three arrays: arrayOne, arrayTwo, and arrayThree:
The sort() method allows us to sort the items in an array into alphabetical or numerical order:





The Logical and Comparison Operators in JavaScript
There are two main groups of operators we’ll look at:
Data comparison operators: Compare operands and return Boolean values.
Logical operators: Test for more than one condition.
Operator Description Example
== Checks whether the left and right operands are equal 123 == 234 returns false.
123 == 123 returns true.
!= Checks whether the left operand is not equal to the
right side
123 != 123 returns false.
123 != 234 returns true.
> Checks whether the left operand is greater than the
right
123 > 234 returns false.
234 > 123 returns true.
>= Checks whether the left operand is greater than or
equal to the right
123 >= 234 returns false.
123 >= 123 returns true.
< Checks whether the left operand is less than the right 234 < 123 returns false.
123 < 234 returns true.
<= Checks whether the left operand is less than, or equal
to, the right
234 <= 123 returns false.
234 <= 234 returns true.



Symbol Operator Description Example in JavaScript
&& And Both conditions must be true. 123 == 234 && 123 < 20 (false)
123 == 234 && 123 == 123 (false)
123 == 123 && 234 < 900 (true)
|| Or Either or both of the conditions
must be true.
123 == 234 || 123 < 20 (false)
123 == 234 || 123 == 123 (true)
123 == 123 || 234 < 900 (true)
! Not Reverses the logic. !(123 == 234) (true)
!(123 == 123) (false)


ExMPLE OF if….else and else if
<html>
<body>
<script type="text/javascript">
var userNumber = Number( prompt( "Enter a number between
1 and 10", "" ) );
if ( isNaN( userNumber ) ){
document.write( "Please ensure a valid number is
entered" );
} else if ( userNumber > 10 || userNumber < 1 ) {
document.write( "The number you entered is not
between 1 and 10" );
} else {
52 CHAPTER 2 DATA AND DECISIONS
document.write( "The number you entered was " +
userNumber );
}
</script>
</body>
</html>


One more thing before we move on: you can break a conditional statement or loop using the
break statement. This simply terminates the block of code running and drops the processing
through to the next statement.

As you’ve already seen, the break statement is great for breaking out of any kind of loop once a
certain event has occurred. The continue keyword works like break in that it stops the execution
of the loop. However, instead of dropping out of the loop, continue causes execution to
resume with the next iteration.


Switch in JavaScript:
The switch statement allows us to “switch” between sections of code based on the value of a
variable or expression. This is the outline of a switch statement:
switch( expression ) {
case someValue:
// Code to execute if expression == someValue;
break; // End execution
case someOtherValue:
// Code to execute if expression == someOtherValue;
break; // End execution
case yesAnotherValue:
// Code to execute if expression == yetAnotherValue;
break; // End execution
default:
// Code to execute if no values matched
}


FOR LOOP in JavaScript

Repeating a Set Number of Times: the for Loop
The for loop is designed to loop through a code block a number of times and looks like this:
for( initial-condition; loop-condition; alter-condition ) {
//
// Code to be repeatedly executed
//
}
// After loop completes, execution of code continues here


While Loop in JavaScript

while ( some condition true ) {
// Loop code
}