Basic Knowledge of JavaScript
JavaScript Notes :
We can start with array :
Array
Every Arrays is JavaScript Object. it just have special properties.
How to declare array in js
var myArray = ["Hello", "Word", "JS"];
console.log(myArray); // [ 'Hello', 10, 'JS' ]
console.log(myArray.length); // 3
console.log(myArray[3]) // undefined
myArray[3] = "foo" // Arrays length keep updating automatically
console.log(myArray.length) // 4
var myArray2 = myArray;
console.log(myArray2[3]);
console.log(myArray[1]); // JS convert automatically number to string, Implecite conversion
console.log(myArray["1"]); // 1
myArray[100] = "Bar";
console.log(myArray); // [ 'Hello', 10, 'JS', 'foo', <96 empty items>, 'Bar' ]
console.log(myArray[99]); // Undefined
console.log(myArray.length); // 101
myArray["foo"] = "abc";
console.log(myArray); // [ 'Hello', 10, 'JS', 'foo', <96 empty items>, 'Bar', foo: 'abc' ]
Arrays Methods :
myArray.push(500); // push function take an argument and that argument as an elementy of the array at the last location.
myArray.pop(); //
myArray.shift()
myArray.unshift(42) // both are equivalence of the push and pop on front right adding and removing element from the front an
var myArray = [10,20,30,34];
console.log(myArray); // [10,20,30,34]
myArray.push(50);
console.log(myArray); // [10,20,30,34,50]
console.log(myArray.pop()); 50
console.log(myArray.shift()); 10
console.log(myArray.unshift(43)); 4
console.log(myArray); // [ 43, 20, 30, 34 ]
Food for Thought
Following is the code to alert max number in an array. Can you think of a way to get the result without using loops? Explore yourself...
var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;i<numbers.length;i++){
if(numbers[i] > max){
max = numbers[i];
}
}
alert(max);
Without loop \
var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){ return b-a});
alert(number[0]); //342
---------------------------------------------------------------------------------------------------------------------------
JS Functions
A function is a set of statement that perform a tasks or calculates a value.
Function may also take inputs, proccess then and return the ouput.
Example of function declaration + definatation
function function_name (Argumetn) {
// function body
}
function_name(arguments);
function hello(string){
return "helllo" + " " + "word";
}
hello("tom");
Function As a value
functions are value in javascript. A javaScript can be assigned as a value to a variable.
var f = function foo(){
console.log("hello");
};
f(); //hello
Function As a Argumetn
var f = function(){
console.log("Hello);
};
var executor = function(fn){
fn();
}
executor(f);
---------------------------
Function As a Property
Function can be added as a property to an object.
var myObje = {
testProp:
};
Function arguments
A function can accept a varied number of arguments. i.e., a function "add" can be called by passing a different number of arguments different times. This is possible using an implicit argument by JavaScript called arguments.
var add = function()
{
var i, sum=0;
for(i=0; i<argument.length; i++){
sum+=argument[i];
}
return sum;
};
console.log(add(1,2,3,4,5));
-----------------------------------------------------------------------------------------------------------------------------
Constructor :
A Constructor is usefull when you want to create multiple similer object with the same properties and methods. The code create an objects as an instans of it.
function car(make, model, year){
this.make=make;
this.model=model;
this.year=year;
}
var car1 = new car('vk','rr',2000);
var car2 = new car('pk','f',2000);
--------------------------------------------------------------------------------------------------------------------------
Arrays forEach Method
One of the popular method in array, 'forEach'
var myArray = [10,20,'hello',{}];
var myfunction = function(item){
console.log("element an arry "+item);
};
myArray.forEach(myfunction);
myArray.forEach(function(item,index,arrays)){
Console.log(item,index);
});
Scope and closure
Scope
Scope refers to the part of the program in which a variable can be accessed.
JavaScript has two types of scopes: Local and Global.
Variables with global scope can be accessed anywhere in the program, and the variables with a local scope can be accessed
within the block or function within which they are declared.
Example Here name1 is a global variable and name2 is a local variable
var name1 = "ben";
myFunction();
function myFunction() {
var name2 = "bob";
console.log(name1);
console.log(name2);
}
console.log(name2);
Console
ben
bob
Uncaught ReferenceError: name2 is not defined
Closure
A Closure is nothing but a function inside another function.
This closure function can access the variables inside its own scope, the outer function's variables and the global variables.
Example
In this example, whenever we call the myClosure function the value of i will be increased by one. i will be set to zero only once and only the inner function will be called everytime when myClosure is called
var myClosure = (function () {
var i = 0;
return function () {return i += 1;}
})();
myClosure();//i=1
myClosure();//i=2
myClosure();//i=3
-------------------------------------------------------
Generatec Random character in JS
function stringGen()
{
var text="";
var len = document.getElementById("num").value;
var c_list = "ABCDEFGHIJKLMNOPQRSTUVWXabcdefghijklmnopqrstuvwxyz0123456789";
for(var i =0; i<len; i++){
text+=c_list.charAt(Math.floor(Math.random() * c_list.length));
}
document.getElementById("result").innerHTML=text;
return text;
}
========================================================================
DOM Manipulation:
Document object Model:
Summarizing DOM
So, to summarize what is DOM,
The HTML DOM is an accepted guideline for how to access, update, add or remove HTML elements.
A Structure representation of an HTML document is provided by DOM.
An HTML document is completely built using objects. DOM represents it in an objected-oriented way which can be manipulated using scripting languages like javascript.
All the objects in the HTML document are hierarchically connected to one another. The document object forms the root of all objects.
There are three kinds of objects:
- Core object (array,math,etc)
- User defined object(myobject,student,employee,etc)
- Host object(h1,document,p,etc)
Data Access By Using Element Id :
prectice.html
<!DOCTYPE HTML>
<html>
<head>
<script src="Code.js"></script>
</head>
<body>
<p id="pera">this is a text</p>
<button onclick="getSubmit()">Submit</button>
</body>
</html>
Code.js
function getSubmit(){
var text = document.getElementById("pera").style.color="blue";
};
Data Access By Using Tag :
prectice.html
<!DOCTYPE HTML>
<html>
<head>
<script src="Code.js"></script>
</head>
<body>
<p id="pera1">this is a text</p>
<p id="pera2">this is a text</p>
<p id="pera3">this is a text</p>
<button onclick="getSubmit()">Submit</button>
</body>
</html>
Code.js
function getSubmit(){
var peragraph = document.getElementsByTagName("p");
for(var i=0; i<peragraph.length; i++)
var text = peragraph[i].style.fontStyle="italic";
}
How to remove HTML element by using Js
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<div id="text">
<p>This is a peragraph</p>
<p id="child"> This is a child</p>
</div>
<script>
var parent= document.getElementById("text");
var child = document.getElementById("child");
parent.removeChild(child);
</script>
</body>
</html>
JavaScript and HTML userInterface
<html>
<head>
<script>
function doSomething(){
alert("Botton2");
};
</script>
</head>
<body>
<button type="button", id="h1" onclick="alert('button1')">Button1</button>
<button type="button", id="h2" onclick="doSomething()">Button2</button>
</body>
</html>
----------------
Create country DropDown field
index.html
<HTML>
<HEAD>
<TITLE> Country field</TITLE>
</HEAD>
<BODY>
Country:
<SELECT NAME="list" ID="list">
<OPTION>India</OPTION>
<OPTION>China</OPTION>
</SELECT>
<input type="text" id="txtbox">
<INPUT TYPE="button" NAME="button" VALUE="Add New" onClick="runList()" />
<script type="text/javascript" src="Code.js"></SCRIPT>
</BODY>
</HTML>
Code.js
function runList(){
var list = document.getElementById("list");
var option = document.createElement("option");
option.innerHTML = document.getElementById("txtbox").value;
list.options.add(option);
}
-----------------------------------------------------------------------------------------------------------------------------
Events & Events Listeners:
Listening for event involves using the addEventListener function:
source.addEventListener(eventname, eventlistener, true);
Reacting to an Evenet:
When an event you are listening for gets overheard, a function known as the event handler will get called.
function normalAndBoring(){
}
An event handler is just a plain ol' fuction. sort of.
---------------------------------------------------------
What is AJAX
Ans: AJAX stand for Asynchronous JavaScript and XML
AJAX uses JavaScript to send and received data without a page refresh
AJAZ is a technology, it's not a programing language.
XMLHttpRequest Object:
//Create an install on the HTTP request object
var xmlhttp = new XMLHttpRequest(); //object
//Specify HTTP GET by defalut and supply the relative url
xmlhttp.open("GET", "game-list.php", false); //method;
//start the synchronous AJAX request and wait for the response
xmlhttp.send(null); /method
var element = document.getElementById("content");
//use the HTML returned from server to create list
element.innerHTML = xmlhttp.resonseText; property
XHR Request
XMLHttpRequest is an object that is used by all modern browsers to communicate with the server.
This object is commonly used in AJAX programming.
You can also update only a part of a web page using this object.
It helps in making synchronous and asynchronous calls to the server and retrieving data without a full page reload.
Let us see how to make synchronous calls and its disadvantages
Example
var request= new XMLHttpRequest();
request.open('GET','Example.txt',false);
request.send();
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.writeln(request.responseText);
}
document.writeln("some text");
In this code, since we passed false as a parameter to open() function the browser treats this as synchronous calls and wait for the server to respond and then execute the next line.
AJAX Requests
Communicate to the server by making the https request
NO need to reload the page.
stand for : Asynchronous javascropt and xml
Updating the DOM
By using the response from the server, you can update the DOM. One way of doing that is by using getElementById. Consider the same example from the previous card
<body>
<p id="myElement"></p>
<script>
var request= new XMLHttpRequest();
request.open('GET','example.txt',true);
request.send();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
console.log(request);
document.getElementById("myElement").innerHTML =request.responseText;
}
};
</script>
</body>
Here the javascript will find the element with the required id and replace it with the response from the server. This can also be done using getElementByTagName which you should be familiar with previous topics.
Reading JSON Files
Now let us see how to read from a JSON file using AJAX. JSON consist of text, it can be converted into javascript object using JSON.parse() method
var request= new XMLHttpRequest();
request.open('GET','example.json',true);
request.send();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200){
var item= JSON.parse(request.responseText)
}
};
Here the variable item has a array of javascript objects where each object has a key value pair from the JSON file. Now you can loop through these object to read the data and use it to update DOM.
var list = '<ul>';
for(var i in item)
{
list += '<li>'+item[i].name+'</li>';
}
Comments
Post a Comment