0% found this document useful (0 votes)
7 views

Web Lecture Week4

Uploaded by

mubashir rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Web Lecture Week4

Uploaded by

mubashir rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Lecture week4: How to Add JavaScript in

HTML Document?

To add JavaScript in HTML document, several method can be used.


These methods include embedding JavaScript directly within
the HTML file or linking an external JavaScript file.
Table of Content
 Inline JavaScript
 Internal JavaScript (Within <script> Tag)
o 1. JavaScript Code Inside <head> Tag
o 2. JavaScript Code Inside <body> Tag
 External JavaScript (Using External File)
 Asynchronous and Deferred JavaScript
Inline JavaScript
You can write JavaScript code directly inside the HTML
element using the onclick, onmouseover, or other event handler
attributes.
HTML
1
<!DOCTYPE html>
2
<html>
3

4
<head>
5
<title>
6
Inline JavaScript
7
</title>
8
</head>
9

10
<body>
11
<h2>
12
Adding JavaScript in HTML Document
13
</h2>
14

15
<button onclick="alert('Button Clicked!')">
16
Click Here
17
</button>
18
</body>
19

20
</html>
Output

For a more comprehensive guide on integrating JavaScript with


HTML, explore our JavaScript Course, which covers everything
from basic scripting to building interactive and dynamic web pages.
Internal JavaScript (Within <script> Tag)
You can write JavaScript code inside the <script> tag within the
HTML file. This is known as internal JavaScript and is commonly
placed inside the <head> or <body> section of the HTML
document.
1. JavaScript Code Inside <head> Tag
Placing JavaScript within the <head> section of an HTML document
ensures that the script is loaded and executed as the page loads.
This is useful for scripts that need to be initialized before the page
content is rendered.
Example: This example shows the addition of a script file inside the
head section.
HTML
1
<!DOCTYPE html>
2
<html>
3

4
<head>
5
<title>
6
Add JavaScript Code inside Head Section
7
</title>
8

9
<script>
10
function myFun() {
11
document.getElementById("demo")
12
.innerHTML = "Content changed!";
13
}
14
</script>
15
</head>
16

17
<body>
18
<h2>
19
Add JavaScript Code
20
inside Head Section
21
</h2>
22

23
<h3 id="demo" style="color:green;">
24
GeeksforGeeks
25
</h3>
26

27
<button type="button" onclick="myFun()">
28
Click Here
29
</button>
30
</body>
31

32
</html>
Output

2. JavaScript
Code Inside <body> Tag
JavaScript can also be placed inside the <body> section of an HTML
page. Typically, scripts placed at the end of the <body> load after
the content, which can be useful if your script depends on the DOM
being fully loaded.
Example: This example shows showing the addition of a script file
inside the body section.
HTML
1
<!DOCTYPE html>
2
<html>
3

4
<head>
5
<title>
6
Add JavaScript Code inside Body Section
7
</title>
8
</head>
9

10
<body>
11
<h2>
12
Add JavaScript Code
13
inside Body Section
14
</h2>
15

16
<h3 id="demo" style="color:green;">
17
GeeksforGeeks
18
</h3>
19

20
<button type="button" onclick="myFun()">
21
Click Here
22
</button>
23

24
<script>
25
function myFun() {
26
document.getElementById("demo")
27
.innerHTML = "Content changed!";
28
}
29
</script>
30
</body>
31

32
</html>
Output

External
JavaScript (Using External File)
For larger projects or when reusing scripts across multiple HTML
files, you can place your JavaScript code in an external .js file. This
file is then linked to your HTML document using the src attribute
within a <script> tag.
Example: This example shows showing the linking of an external
script file inside the head section.
HTMLJavaScript
1
<!DOCTYPE html>
2
<html>
3

4
<head>
5
<title>
6
External JavaScript
7
</title>
8
<script src="script.js"></script>
9
</head>
10

11
<body>
12
<h2>
13
External JavaScript
14
</h2>
15

16
<h3 id="demo" style="color:green;">
17
GeeksforGeeks
18
</h3>
19

20
<button type="button" onclick="myFun()">
21
Click Here
22
</button>
23
</body>
24

25
</html>
Output:

Advantages of External JavaScript


 Faster Page Load Times: Cached external JavaScript files
don’t need to be reloaded every time the page is visited,
which can speed up loading times.
 Improved Readability and Maintenance: Keeping HTML
and JavaScript separate makes both easier to read and
maintain.
 Separation of Concerns: By separating HTML (structure)
and JavaScript (behavior), your code becomes cleaner and
more modular.
 Code Reusability: One external JavaScript file can be
linked to multiple HTML files, reducing redundancy and
making updates easier.
Asynchronous and Deferred JavaScript
JavaScript can be loaded asynchronously or deferred to optimize
page performance, especially for larger scripts. By default,
JavaScript blocks the rendering of the HTML page until it is fully
loaded, but using async or defer can help improve load times.
1. async Attribute
The async attribute loads the script asynchronously, meaning the
script will be downloaded and executed as soon as it is available,
without blocking the page.
<script src="script.js" async></script>
2. defer Attribute
The defer attribute delays the execution of the script until the entire
HTML document has been parsed. This is particularly useful for
scripts that manipulate the DOM.
<script src="script.js" defer></script>
How to Reference External JavaScript Files?
We can reference an external script in three ways in javascript:
 By using a full URL:
src = "https://www.geeksforgeek.org/js/script.js"
 By using a file path:
src = "/js/script.js"
 Without using any path:
src = "script.js"

JavaScript Syntax
Last Updated : 12 Aug, 2024


JavaScript syntax refers to the rules and conventions dictating how


code is structured and arranged within the JavaScript programming
language. This includes statements, expressions, variables,
functions, operators, and control flow constructs.
Syntax
console.log("Basic Print method in JavaScript");
JavaScript syntax refers to the set of rules that determines
how JavaScript programs are constructed:
// Variable declaration
let c, d, e;

// Assign value to the variable


c = 5;

// Computer value of variables


d = c;
e = c / d;
JavaScript Values
There are two types of values defined in JavaScript Syntax:
 Fixed Values: These are known as the literals.
 Variable values: These are called variables
These are the features of JavaScript which have some predefined
syntax:
Table of Content
 JavaScript Literals
 JavaScript Variables
 JavaScript Operators
 JavaScript Expressions
 JavaScript Keywords
 JavaScript Comments
 JavaScript Data Types
 JavaScript Functions
 JavaScript Identifiers
JavaScript Literals
Syntax Rules for the JavaScript fixed values are:
 JavaScript Numbers can be written with or without decimals.
 Javascript Strings are text that can be written in single or
double quotes.
JavaScript
1
let num1 = 50
2
let num2 = 50.05
3

4
let str1 = "Geek"
5
let str2 = 'Geeks'
6

7
console.log(num1)
8
console.log(num2)
9
console.log(str1)
10
console.log(str2)

Output
50
50.05
Geek
Geeks
JavaScript Variables
A JavaScript variable is the simple name of the storage location
where data is stored. There are two types of variables in JavaScript
which are listed below:
 Local variables: Declare a variable inside of a block or
function.
 Global variables: Declare a variable outside function or
with a window object.
Example: This example shows the use of JavaScript variables.
JavaScript
1
// Declare a variable and initialize it
2
// Global variable declaration
3
let Name = "Apple";
4

5
// Function definition
6
function MyFunction() {
7

8
// Local variable declaration
9
let num = 45;
10

11
// Display the value of Global variable
12
console.log(Name);
13

14
// Display the value of local variable
15
console.log(num);
16
}
17
18
// Function call
19
MyFunction();
Output:
Apple
45
JavaScript Operators
JavaScript operators are symbols that are used to compute the value
or in other words, we can perform operations on operands.
Arithmetic operators ( +, -, *, / ) are used to compute the value, and
Assignment operators ( =, +=, %= ) are used to assign the values
to variables.
Example: This example shows the use of javascript operators.
JavaScript
1
// Variable Declarations
2
let x, y, sum;
3

4
// Assign value to the variables
5
x = 3;
6
y = 23;
7

8
// Use arithmetic operator to
9
// add two numbers
10
sum = x + y;
11

12
console.log(sum);

Output
26
JavaScript Expressions
Javascript Expression is the combination of values, operators, and
variables. It is used to compute the values.
Example: This example shows a JavaScript expression.
JavaScript
1
// Variable Declarations
2
let x, num, sum;
3

4
// Assign value to the variables
5
x = 20;
6
y = 30
7

8
// Expression to divide a number
9
num = x / 2;
10

11
// Expression to add two numbers
12
sum = x + y;
13

14
console.log(num + "\n" + sum);

Output
10
50

JavaScript Keywords
The keywords are the reserved words that have special meanings in
JavaScript.
// let is the keyword used to
// define the variable
let a, b;

// function is the keyword which tells


// the browser to create a function
function GFG(){};
JavaScript Comments
The comments are ignored by the JavaScript compiler. It increases
the readability of code. It adds suggestions, Information, and
warning of code. Anything written after double slashes // (single-line
comment) or between /* and */ (multi-line comment) is treated as a
comment and ignored by the JavaScript compiler.
Example: This example shows the use of javascript comments.
JavaScript
1
// Variable Declarations
2
let x, num, sum;
3

4
// Assign value to the variables
5
x = 20;
6
y = 30
7

8
/* Expression to add two numbers */
9
sum = x + y;
10

11
console.log(sum);

Output
50

JavaScript Data Types


JavaScript provides different datatypes to hold different values on
variables. JavaScript is a dynamic programming language, which
means do not need to specify the type of variable. There are two
types of data types in JavaScript.
 Primitive data type
 Non-primitive (reference) data type
// It store string data type
let txt = "GeeksforGeeks";

// It store integer data type


let a = 5;
let b = 5;

// It store Boolean data type


(a == b )

// To check Strictly (i.e. Whether the datatypes


// of both variables are same) === is used
(a === b)---> returns true to the console

// It store array data type


let places= ["GFG", "Computer", "Hello"];

// It store object data (objects are


// represented in the below way mainly)
let Student = {
firstName: "Johnny",
lastName: "Diaz",
age: 35,
mark: "blueEYE"
}
JavaScript Functions
JavaScript functions are the blocks of code used to perform some
particular operations. JavaScript function is executed when
something calls it. It calls many times so the function is reusable.
Syntax:
function functionName( par1, par2, ....., parn ) {
// Function code
}
The JavaScript function can contain zero or more arguments.
Example: This example shows the use of Javascript functions.
JavaScript
1
// Function definition
2
function func() {
3

4
// Declare a variable
5
let num = 45;
6

7
// Display the result
8
console.log(num);
9
}
10

11
// Function call
12
func();

Output
45

JavaScript Identifiers
JavaScript Identifiers are names used to name variables and
keywords and functions.
A identifier must begin with:
 A letter(A-Z or a-z)
 A dollar sign($)
 A underscore(_)
Note: Numbers are not allowed as a first character in JavaScript
Identifiers.
JavaScript Case Sensitive
JavaScript Identifiers are case-sensitive.
Example: Both the variables firstName and firstname are different
from each other.
JavaScript
1
let firstName = "Geek";
2
let firstname = 100;
3
4
console.log(firstName);
5
console.log(firstname);

Output
Geek
100

JavaScript Camel Case


In JavaScript Camel case is preferred to name a identifier.
Example:
let firstName
let lastName
JavaScript Character Set
A unicode character set is used in JavaScript. A unicode covers the
characters, punctuations and symbols.
We have a complete article on character sets. Click here to
read Charsets article.
JavaScript Syntax – FAQs
What is the basic syntax of JavaScript?
The basic syntax of JavaScript includes statements, expressions,
variables, functions, operators, and control flow constructs. A typical
JavaScript statement ends with a semicolon and can include
variable declarations, function calls, loops, and conditionals.
What is the syntax for defining a JavaScript function?
The syntax for defining a function in JavaScript is:
function functionName(parameter1, parameter2) {
// Code to be executed
}
This function can then be called using functionName(argument1,
argument2);.
Is JavaScript syntax easy to learn?
Yes, JavaScript syntax is considered easy to learn, especially for
beginners. It is intuitive and has a C-like structure, which is familiar
to those who have experience with languages like C, C++, or Java.
What is the JavaScript syntax for embedding code in
HTML?
JavaScript code is embedded in HTML using the <script> tag. The
script can be placed within the <head> or <body> sections of the
HTML document, or it can be included as an external file:
<script>
// JavaScript code here
</script>
What does “syntax” mean in coding?
In coding, “syntax” refers to the set of rules that defines the
structure and format of the code in a programming language. It
dictates how code should be written so that it can be correctly
interpreted and executed by the compiler or interpreter.

You might also like