Friday, 22 November 2013

Javascript Fundamental

1. Difference between ondocumentready and window.onload  

window.onload :this fires after all images , css and reference load .It is fired later
ondocumentready :this fires after DOM load , fired first

 Then ondocumentready is far better option to manipulate pages

2. Difference between Jscript and Javascript

Both are similar 
Jscript: Developed by Microsoft , for internet explorer
Javascript : Developed by  Netscape ,for Mozilla

3) How to detect a variable is object ?
   var obj
    typeof obl === "object"

4) undefined and null
Undefined : A variable is declared but not assign a value
null: A assigned value,It can be assigned to a variable as a representation of no value.


5) “==” and “===”
 “==” :check the equality
 “===” :check the equality as well as type

6) This keyword
This keyword refer to current object

Example 1.
In a page this is written 
this.student_name : will refer the variable (student_name)  of   current page 


Example2.
In a function this is written 
this.student_name : will refer the variable (student_name)  of   current function

 7) IsNan() function
IsNan stands for not a number.It check a variable /value is number or not
alert(isNaN(“red”)) will return true
alert(isNaN(5)) will return false

8) decodeURI(), encodeURI()
A url can not be send in a  in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI  to and from a format that can be sent via a URI.
<script type="text/javascript">
var myurl = "http://www.google.com/search?key=A6p-jeArypeJW5-GHWai56-ASIowYjw5"
document.write(myurl );
document.write("encoded: "+encodeURI(myurl ));
</script>

9)What is eval()
eval is a method ,it has power to execute small amount/space of code during execution
<script type="text/javascript">
var myvar = "this my javascript";
document.write(eval(myvar ));
</script>
Result
this my javascript

10)Javascript object properties
var obj  // object declared

Set the value
obj.name="Maria Gomes"
obj.age="17"
obj.sex="female"

Get the value
document.write(obj.name);
document.write(obj.age);
document.write(obj.sex);
 


11) Event Handlers &  addEventListener

We can add event handler in javascript also
Example 1.
function defined separately
document.getElementById("myControl").onclick = myfunction;

function myfunction()
{
alert('function is working') ;
//define function here
}


Example 2.
function defined included
document.getElementById("myControl").onclick = function ()
{
alert('function is working') ;
//define function here
 }

Examplie 3.
addEventListener , but does not work in IE yet
if(document.getElementById("myControl").addEventListener)
   {
    document.getElementById("myControl").addEventListener("click", myfunction, false);
 }
function myfunction()
{
alert('function is working') ;
//define function here
}

12)How to convert numbers to strings and  strings to numbers 

//number to string
var myvalue = "14";
var mystring = myvalue .toString()

// string to number
var myvalue = "14";
var mynumber=parseInt(myvalue )

13) What is shift and unshift

var numbers = ["A", "B", "C", "D"];
numbers.unshift("A");
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
Output
B,C,D

14)cookies stored in the location
Mozila
c:\Program Files\Netscape\Users\username\cookies.txt
IE
 c:\Windows\Cookies\username@Websitename.txt --file

15) exception handling in javascript
Like java,C,C# javascript also uses exception handling by try,catch, finally

try
{
//Code to execute
}
catch(e)
{
//exeption part
}
finally
{
//finalized
 }


16) window.navigator
this code is used to get information of user browser
navigator.appName-->Browser Name
navigator.appVersion-->Browser Version
navigator.systemLanguage-->User -Agent Language
navigator.cookieEnabled--->Browser cookie enabled ot not
 

 17)How to stop Execution of setTimeout()
 window.clearTimeout(interval


18) for each loop in javascript

var obj = {prop1: 12, prop2: 24, prop3: 36}; 
for each (var item in obj)  
{
  document.write (item);
}

19) Recursion  in JavaScript

calling a function repetedly

var reverseArray = function(x,indx,str) 
{
    if (indx === 0) { // Termination condition
        return str; // return default
    } else {
        return reverseArray(x, --indx, str + " " + x[indx]); 
    }
}


20) Javascript key detection
It is a easy way to detect which key was press.As like normal programming languages like C#, vb.net , they
same way developer can detect key .There are two different type of way to detect key press and other event like mouse click, mouse over.
keyCode and charCode are the keyword to detect event .Some browser support keyCode , some charCode.

we can detect this by

var myCode;

if ( e.keyCode )
{
    myCode= e.keyCode;
}
else
{
    myCode= e.charCode;
}

in short form
var myCode= e.keyCode ? e.keyCode : e.charCode
e stands for event.

Here is an example how to detect the event

<script type="text/javascript">
function detectcode(e){
var myCode=e.keyCode? e.keyCode : e.charCode
alert(myCode)
}
</script>
<form>
<input type="text"  onkeyup="detectcode(event);" />
</form>
 
This example will return alert box the code of when a key press on the textbox

Now , there are some other ways to detect keys ie, Alt, Shift, Ctrl
 
here is an example
function detectcode(e)
{
var eventtobj=window.event? event : e
if (eventtobj.altKey || eventtobj.ctrlKey || eventtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectcode
</script> 
 
 charCode works NS/Firefox only
 
 
 
Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222



21) DOM Element properties
 attributes[] :Returns the array of attributes

         var obj=document.getElementById("myimage").attributes;
         var  objval= obj[0].value;
         var  objname= obj[0].name;
         var  objsrc= obj[0].src; 
        
childNodes[] :Returns the array of childndes

     var obj=document.getElementById("someList").attributes;
     for (i=0; i<obj.childNodes.length; i++)
   {
       if (obj.childNodes[i].nodeName=="LI")
   }

className :Returns css class name of the object
 var objclass=document.getElementById("myobject").className;

clientWidth  &  clientHeight :Returns viewable width ,height of the content on the page
 does not consider scrollbars,borders, margins
 var vwidth=document.body.clientWidth 
 var vheight=document.body.clientHeight

dir :Returns text direction left to write and right to left.Terms as ltr,rtl
 document.getElementById("mytext").dir="rtl"



firstChild :Returns the first child of the node
    var obj=document.getElementById("mytext").firstChild;
    obj contain first child of  mytext

innerHTML :Return the html string contain by the object;
var myhtml="<p>I am learing javascript<p><b>How am i learing ?"
document.getElementById("myDiv").innerHTML=myhtml ;

offsetLeft & offsetTop & offsetParent & offsetWidth & offsetHeight
 offset position of the current element relative to its offset container.Left,top,Parent object , width, height of
the object related to the parent who contains it

<body>
<form id="myform">
<div id="offset_test">This is my test control</div>
</form>
<body>

<script type="text/javascript">
        var objleft  =document.getElementById("offset_test").offsetLeft ;
        var objtop=document.getElementById("offset_test").offsetTop ;
        var objparent=document.getElementById("offset_test").offsetParent ;
        var objwidth=document.getElementById("offset_test").offsetWidth ;
        var objheight=document.getElementById("offset_test").offsetHeight;
</script>


scrollLeft &  scrollTop & scrollHeight & scrollHeight


22) SessionStorage & LocalStorage 
Both  allows to save key/value pairs in a web browser. The value must be a string, and save js objects 
var user = {'abc':'cde'};
sessionStorage.setItem('user', user);
var obj = sessionStorage.user; 

23) How to set and get values of cookies ?
cookies are data , which stored in your local computer , as a text file.cookies are set on local machine , i.e client machine only

 document.cookie="YourName=Joe Smith";

23)How to add html object in javascript with value

There is the code

function add_Form_Field(form_object, field_type, field_name, field_value) {
            if (form_object) {
                var input = document.createElement('INPUT');
                if (document.all) {
                    input.type = field_type;
                    input.name = field_name;
                    input.value = field_value;
                } else if (document.getElementById) {
                    input.setAttribute('type', field_type);
                    input.setAttribute('name', field_name);
                    input.setAttribute('value', field_value);
                }
                form_object.appendChild(input);
            }
        }
form_object=ID of form
field_type=textbox,listbox,option ect
field_value=Value of the field

24)Form action Property


Set the action property URL of a form

document.getElementById("FormToken").action="../All_Pages/myForm.aspx";

The action property sets or returns the value of the action attribute in a form.
The action attribute specifies where to send the form data when a form is submitted.


var my_action = document.getElementById("myForm").action;

Return the URL for where to send the form data when a form is submitted

25) Form target Property


_blank
Opens in a new window
_self
Opens in the same frame as it was clicked (default)
_parent
Opens in the parent frameset
_top
Opens in the full body of the window
framename
Opens in a named frame









formObject.target="_blank|_self|_parent|_top|framename"

Change where to display the response that is received after submitting a form (open the response in a new window instead of the same frame as it was clicked):


26)  document.getElementById and document.all


           if (document.getElementById)
              div = document.getElementById('popupWindow' + n);
          else if (document.all)
              div = document.all['popupWindow' + n];

document.getElementById, one of the primary methods of the DOM that any modern browser supports
 document.all is a proprietary property of IE introduced in IE4

27) Switch statement of javascript

function MyObjectType(obj) 
{
    switch (obj.constructor) {
        case Date:
            document.write("Object is a Date.");
            break;
        case Number:
            document.write("Object is a Number.");
            break;
        case String:
            document.write("Object is a String.");
            break;
        default:
            document.write("Object is unknown.");
    }
}
 
28) IIF 

var a = 2;
var b = 0;
var c = (a > b || b == 0)? "do something" : "do something else";

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...