0% found this document useful (0 votes)
68 views37 pages

JavaScript Basics for Web Development

JavaScript is a crucial programming language for web development, enabling interactivity and dynamic content on web pages. It allows developers to manipulate HTML and CSS, respond to user events, and manage data types and variables. The document covers fundamental concepts including functions, events, and the use of external scripts, emphasizing JavaScript's versatility and importance in creating engaging web applications.

Uploaded by

bababhosdidas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views37 pages

JavaScript Basics for Web Development

JavaScript is a crucial programming language for web development, enabling interactivity and dynamic content on web pages. It allows developers to manipulate HTML and CSS, respond to user events, and manage data types and variables. The document covers fundamental concepts including functions, events, and the use of external scripts, emphasizing JavaScript's versatility and importance in creating engaging web applications.

Uploaded by

bababhosdidas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to JavaScript

JavaScript
JavaScript is the programming language of HTML and the Web.

JavaScript is easy to learn.

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages


JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":

<!DOCTYPE html><html><body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='[Link]("demo").innerHTML = "Hello


JavaScript!"'>Click Me!</button>

</body></html>
JavaScript accepts both double and single quotes.
The onclick event of the button element expects JavaScript code that is triggered when
the button is clicked upon. So we put the function that needs to be called in the onclick
property as well.
<button onclick = "fun()" > Click Me </button>
More options are provided to customize the execution of the JavaScript functions in
different ways. for example, we can also set the function to be called only when the
button is double-clicked. This can be done with the "ondblclick" event of the button
tag.
<button ondblclick = "fun()" > Click Me

Buttons can also be part of forms that do some sort of validation and form submission.
Buttons can also be created using the input tag provided by HTML. The onclick event
attribute is again configured to handle the behavior of the button.

Syntax
<input type = "button" onclick = "fun()" value = "Button_Name" >
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

<!DOCTYPE html><html><body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="[Link]('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="[Link]('myImage').src='pic_bulboff.gif'">
Turn off the light</button></body></html>
JavaScript Where To
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">hello saransh</p>
<script>
[Link]("demo").innerHTML = "My First JavaScript";

</script>
<p id="demo">hello saransh</p>
</body></html>

JavaScript may use a type attribute: <script type="text/javascript">.

The type attribute is not required. JavaScript is the default scripting language in HTML.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when
"called“.

For example, a function can be called when an event occurs, like when the user
clicks a button.

Scripts can be placed in the <body>, or in the <head> section of an HTML page,
or in both.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head>
section of an HTML page.

The function is invoked (called) when a button is clicked:


Event Description
keyup Fires when a key is released.
click Fires when an element is clicked.
Fires when a key is pressed down
Fires when an element is double- keypress
dblclick and released.
clicked.
Fires when an element receives
Fires when a mouse button is focus
mousedown focus.
pressed down on an element.
blur Fires when an element loses focus.
Fires when a mouse button is
mouseup Fires when the value of an input
released on an element. change
element changes.
Fires when the mouse pointer
mousemove submit Fires when a form is submitted.
moves over an element.
Fires when the value of an input
Fires when the mouse pointer input
mouseover element changes.
moves onto an element.
Fires when the browser window is
Fires when the mouse pointer resize
mouseout resized.
moves off an element.
Fires when an element’s scrollbar is
Fires when the mouse pointer scroll
mouseenter scrolled.
enters an element.
Fires when a web page or an image
Fires when the mouse pointer load
mouseleave is finished loading.
leaves an element.
Fires when a web page is about to
keydown Fires when a key is pressed down. unload
be unloaded.
<p id = "para" onscroll = "fun()"> Hi, Welcome to the [Link].
This site is developed so that students may learn computer science
related technologies easily. The [Link] is always providing an
easy and in-depth tutorial on various technologies. No one is perfect in
this world, and nothing is eternally best. But we can try to be better.
</p>
<script>
function fun() {
[Link]("para").[Link] = "red";
[Link]("para").[Link] = "lightgreen";
}
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h1>A Web Page</h1>


<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try 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 (called) when a button is clicked:
<!DOCTYPE html>
<html><body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</body></html>

Placing scripts at the bottom of the <body> element improves the display speed, because
script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
}
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 src (source) attribute of a
<script> tag:
<!DOCTYPE html><html><body>
<script src="[Link]"></script>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "[Link]")</p>
</body></html>
You can place an external script reference in <head> or <body> as you like.

External JavaScript Advantages

Placing scripts in external files has some advantages:

It separates HTML and code


It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:
<script src="[Link]"></script>
<script src="[Link]"></script>
JavaScript Display Possibilities
JavaScript can "display" data in different ways:

Writing into an HTML element, using innerHTML.


Writing into the HTML output using [Link]().
Writing into an alert box, using [Link]().
Writing into the browser console, using [Link]().
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
[Link]("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
[Link](5 + 6);
Using [Link]() after an HTML document is loaded, will delete all existing HTML:

<button type="button" onclick="[Link](5 + 6)">Try it</button>


</script>

</body>
</html>
You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods. You cannot access output devices from JavaScript.
The only exception is that you can call the [Link]() method in the browser to print the content of the
current window.

<!DOCTYPE html>
<html>
<body>

<h2>The [Link]() Method</h2>

<p>Click the button to print the current page.</p>

<button onclick="[Link]()">Print this page</button>

</body>
</html>
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a
computer.

In a programming language, these programming instructions are called


statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.


JavaScript Statements

JavaScript statements are "instructions" to be "executed" by the web browser.

JavaScript statements are composed of:


Variables, Values, Operators, Expressions, Keywords, and Comments.

The statements are executed, one by one, in the same order as they are written.
Add a semicolon at the end of each executable statement:

var a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
do ... while Executes a block of statements, and repeats the block, while a condition is true

for Marks a block of statements to be executed, as long as a condition is true

function Declares a function


if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function


switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable


In a programming language, variables are used to store data values.

JavaScript uses the var keyword to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

var x;
x = 6;

JavaScript uses arithmetic operators ( +, - ,* , / ) to compute values.

JavaScript uses an assignment operator ( = ) to assign values to variables:

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed.


JavaScript identifiers
In JavaScript, identifiers are used to name variables (and keywords, and functions, and
labels).

The rules for legal names are much the same in most programming languages.

In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($).

Subsequent characters may be letters, digits, underscores, or dollar signs.

All JavaScript identifiers are case sensitive.

JavaScript uses the Unicode character set.


JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like "John
Sharma".

In programming, text values are called text strings.

Strings are written inside double or single quotes.

Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
var carName = "Volvo";
[Link]("demo").innerHTML = carName;
</script>

</body>
</html>
var person = "John Doe", carName = "Volvo", price = 200; <!DOCTYPE html>
<html>
var person = "John Doe",
<body>
carName = "Volvo",
price = 200;
<h2>JavaScript Variables</h2>

A variable declared without a value will have the value <p>If you re-declare a JavaScript variable, it will
undefined. not lose its value.</p>

<p id="demo"></p>
If you re-declare a JavaScript variable, it will not lose its value.
<script>
var carName = "Volvo";
The variable carName will still have the value "Volvo" after the var carName;
execution of these statements: [Link]("demo").innerHTML
= carName;
</script>

</body>
</html>
JavaScript evaluates expressions from left to right.

Different sequences can produce different results:

var x = "5" + 2 + 3; // 523


var x = 2 + 3 + "5"; // 55

var $$$ = "Hello World";


var $ = 2;
var $myMoney = 5;
JavaScript Types are Dynamic <!DOCTYPE html>
<html>
<body>

JavaScript has dynamic types. This <h2>JavaScript Data Types</h2>


means that the same variable can <p>JavaScript has dynamic types. This means that the same
be used to hold different data variable can be used to hold different data types:</p>
types:
<p id="demo"></p>

<script>
var x; // Now x is undefined var x; // Now x is undefined
x = 5; // Now x is a Number x = 5; // Now x is a Number
x = "John"; // Now x is a String
x = "John"; // Now x is a String
[Link]("demo").innerHTML = x;
</script>

</body>
</html>
JavaScript Strings
• A string (or a text string) is a series of characters like "John Doe".

• Strings are written with quotes. You can use single or double
quotes:

var carName1 = "Volvo XC60"; // Using double quotes


var carName2 = 'Volvo XC60'; // Using single quotes

You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
var answer1 = "It's alright"; // Single quote inside double
quotes
var answer2 = "He is called 'Johnny'"; // Single quotes inside
double quotes
var answer3 = 'He is called "Johnny"'; // Double quotes inside
single quotes
JavaScript Numbers <!DOCTYPE html>
<html>
• JavaScript has only one type of numbers. <body>

• Numbers can be written with, or without <h2>JavaScript Booleans</h2>


decimals:
<p>Booleans can have two values: true or
var x1 = 34.00; // Written with decimals false:</p>
var x2 = 34; // Written without
decimals <p id="demo"></p>

<script>
var x = 5;
JavaScript Booleans var y = 5;
var z = 6;
var x = 5; [Link]("demo").innerHTML =
var y = 5; (x == y) + "<br>" + (x == z);
var z = 6; </script>
(x == y) // Returns true </body>
(x == z) // Returns false </html>
• Booleans are often used in conditional testing.

JavaScript Arrays
JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars,


containing three items (car names):
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is
[0], second is [1], and so on.
JavaScript Objects
<!DOCTYPE html>
JavaScript objects are written with curly <html>
braces {}. <body>

<h2>JavaScript typeof</h2>
<p>The typeof operator returns the type of a
Object properties are written as name:value variable or an expression.</p>
pairs, separated by commas.
<p id="demo"></p>
var person = {firstName:"John",
lastName:"Doe", age:50, eyeColor:"blue"}; <script>
[Link]("demo").innerHTML =
typeof "" + "<br>" +
typeof "John" + "<br>" +
The typeof Operator typeof "John Doe";
</script>
You can use the JavaScript typeof operator </body>
to find the type of a JavaScript variable. </html>
typeof 0 // Returns "number"
typeof 314 // Returns "number"
The typeof operator returns the type of a typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
variable or an expression: typeof (3 + 4) // Returns "number"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
var car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
car = undefined; // Value is undefined, type is undefined

Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
var car = ""; // The value is "", the typeof is "string“

Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.

You can empty an object by setting it to null:


var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
<!DOCTYPE html><html><body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
[Link]("demo").innerHTML = myFunction(4, 3);
</script></body></html>
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, 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 listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something"
invokes (calls) 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 a return statement, the function will stop
executing.

Functions often compute a return value. The return value is


"returned" back to the "caller“.
<!DOCTYPE html><html><body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
var x = myFunction(4, 3);
[Link]("demo").innerHTML = x;
</script></body></html>

You might also like