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

Javascript

This document covers the fundamentals of JavaScript within HTML documents, emphasizing its importance for adding interactivity and dynamic functionality to web pages. It explains how to write JavaScript programs, including the use of the <script> tag, external JavaScript files, and the object model in JavaScript. Additionally, it highlights the document.write() method and provides guidelines for writing JavaScript code effectively.

Uploaded by

yllx968
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)
7 views

Javascript

This document covers the fundamentals of JavaScript within HTML documents, emphasizing its importance for adding interactivity and dynamic functionality to web pages. It explains how to write JavaScript programs, including the use of the <script> tag, external JavaScript files, and the object model in JavaScript. Additionally, it highlights the document.write() method and provides guidelines for writing JavaScript code effectively.

Uploaded by

yllx968
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
You are on page 1/ 61

Unit 5

Java Script in
HTML Documents
page (84)
Learning Objectives
You will learn about:
► the importance of JavaScript
► writing a JavaScript program
► using an external Java script file
► the object model in JavaScript
► the document.write() method
► Java Script variables and operators.
SNAP RECAP: To assess you pre- knowledge
► list the elements of HTML you have learned so far .

Element is everything from the start tag to the end tag.

<Tag Name>...</Tag Name>


<p>...</p>
<font>...</font>
.
.
<table>...<table>
SNAP RECAP:
► What do you think is a limitation of HTML script?

• HTML is essential to create the structure and design of a web


page.(Formatting the web pages)

• HTML has limitations when it comes to interactivity and


dynamic functionality.

• HTML can create static web pages (one-way instructions) in a


one style.
Introduction:
▪ HTML is a very limited document formatting language it's based on tags that
instruct the browser how to display text or an image .

▪ HTML is limited to a static, one-way interaction with the user .

▪ To add functionality to your work page you need a scripting language.

▪ JavaScript is one of the most popular scripting language for the internet it
works in all major browsers such as :

► Internet Explorer
► Firefox
► Chrome
► Opera and Safari
The Main Objective in this Chapter:
▪ We will learn how to add functionality to your webpages ,using JavaScript.

▪ Ability to create interactive elements,Perform a calculation ,Dealing with events


Interaction with external resources
▪ There are many things that can be created with JavaScript that cannot be achieved
with HTML alone.
▪ what JavaScript can do.
▪ JavaScript Can Change HTML Content .
▪ JavaScript Can Change HTML Attribute Values.
▪ JavaScript Can Change HTML Styles (CSS).
▪ JavaScript Can Hide HTML Elements.
https://www.w3schools.com/js/js_intro.asp
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

▪ Don't confuse JavaScript with Java language both share


similar names but are different in most aspects.
▪ JavaScript is easy to learn.
Commonly Asked Questions:
▪ How do I get JavaScript?

▪ Where can I download JavaScript?

▪ Is JavaScript Free?

✔ You don't have to get or download JavaScript.


✔ JavaScript is already running in any browser on your computer, on your tablet, and
on your smart-phone.
✔ JavaScript is free to use for everyone.
Java Script:
▪ In this chapter you will learn how to add functionality to your work pages by
using JavaScript.
▪ JavaScript is a scripting language with a very simple syntax .
▪ It's used to add interactivity to your web page .
▪ JavaScript is set to execute when changes need to be reflected on the web
page, such as ,when a page has finished loading or when a user clicks on a
HTML element .
Example:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onload
Interaction with Java Script:
▪ JavaScript is set to execute when changing changes need to be reflected on the web page,
such as ,when a page has finished loading or when a user clicks on a HTML element .

This type of interaction requires knowledge of constructs or the structures such as


if Statement or For loops which are not part of the HTML syntax

▪ if (hour < 18) {


▪ _ex for (let i = 0; i <
greeting = "Good day";
cars.length; i++) {
} else {
text += cars[i] + "<br>";
greeting = "Good evening";
}
}
Java Script:
▪ JavaScript provides web page authors with the power

to reach a very high level of interaction between the

user and the document . is often the company


or organization that
▪ JavaScript is lines of executable computer code created the page

usually embedded directly in HTML pages.


<html>
<script language="JavaScript">
………
</script>
</html>
Java Script:
▪ The importance of a JavaScript :
JavaScript is used because:
❖ It helps to add interactive element to HTML pages.
❖ It is a scripting language which is also a light weight
programming language • Designed to have a small memory
footprint.
❖ Everyone can use java script without purchasing the • Important when porting a language
into a different computer system.
license
❖ It is supported by all major browsers such as Internet
explorer Firefox chrome opera and Safari.
Writing a Java Script program:
The <script> Tag
▪ JavaScript statements can be included in HTML documents by enclosing the statements
between an opening <script>tag and a closing</script>tag.
▪ The section between the opening tag and the closing tag is called scripting block.
For example:
<html>

<script language="JavaScript">
…… The section is called
[JavaScript statements] scripting block.
……
</script>

</html>
JavaScript may be placed in either the in
<head> or <body>

• You can place any number of <script> tag in an HTML document.


• Scripts can be placed in the <body> or in the <head> section of an HTML
page, or in both.
• the script code can be broken into small parts and the place in different
sections of the HTML document to have different section start each with the
<script> tag and close it with the closing tag </script>
The script code can be broken into small parts :
<html>

<script language="JavaScript">
………
</script> different sections

<script language="JavaScript">
………
</script>

</html>

• It's recommended to keep all the JavaScript code together in one single
section of the document this is done for better readability and
understanding.
JavaScript Where To:
1) JavaScript in <head>

2) JavaScript in <body>

3) Or in both

4) External JavaScript
1) JavaScript in <head>
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
For example:
<html>
<head>

<script language="JavaScript"> The <head> section


………
</script>

</head>
<body>
………
</body>
</html>
2) JavaScript in <Body>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
For example:
<html>
<head>
…………
</head>
<body>

<script language="JavaScript"> The <body> section


…………
</script>

</body>
</html>
3) JavaScript in both
In this example, a JavaScript function is placed in the <head> section and in <body>
section of an HTML page.
For example:
<html>
<head>
<script language="JavaScript">
…………
</script> In both sections
</head>
<body>
<script language="JavaScript">
…………
</script>
</body>
</html>
4)Using an external JavaScript file
• JavaScript can also be placed in external files:
• To use the external Script ,point to the .js file in the ‘src’ attribute of the script tag
in a HTML document.
for example:

</html>
<script language="JavaScript" src="Myscript.js">

[additional JavaScript statement]


How to call the Myscript.js
</script> file in the HTML document
</html>
External file with name myScript.js
• You can write a JavaScript in an external file, the external file is simply a text
file ,we can write the file using the notepad application containing JavaScript
code with a .js file extension
• External scripts are practical when the same code is used in many different
web pages.
• External scripts cannot contain <script> tags

X
<script language="JavaScript">
External scripts cannot
contain <script> tags
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
X
</script>
Searching information (5mins)

Task:
Placing scripts in external files has some
advantages(use the internet to search
for some) and then discussing them with
your colleague.
External file with name myScript.js

External scripts
cannot
contain <script> tags

Save the file with .js


extension
Using an external JavaScript file in HTML Document:

Calling an External
scripts (Myscript.js) in
HTML Document

HTML Document
3) Using an external JavaScript file
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
• If you want to run the same JavaScript on several pages without having to write the same script on
every page
An external script can be referenced in 3 different ways:
• With a file path (like /js/) : <script src="/js/myScript.js"></script>

• Without any path : <script src="myScript.js"></script> commonly used

• With a full URL : <script src="https://www.w3schools.com/js/myScript.js"></script>


Summary of using an external JavaScript file
• If you want to run the same JavaScript on several pages without having to try the
same script on every page .
• you can write a JavaScript in an external file the external file is simply a text file
containing JavaScript code with a .js file extension
• To use the external Script ,point to the .js file in the ‘src’ attribute of the script tag
for example
• JavaScript files have an extension of those .js and are identified by an icon .
• These files contain just the code and no script tag is required.
Rules for writing a JavaScript program :

You should follow the rules given below when writing a program using
JavaScript:
• The scripting language has to be written within <script>tag and
</script>tag in a HTML document.

• The <script>…..</Script>tags can either be written in the


<head> or <body> of the html document.

• A program can have more than one of the


<script>…..</Script>tags.
Rules for writing a JavaScript program :
You should follow the rules given below when writing a program using
JavaScript:
• JavaScript is a case sensitive language.

• JavaScript is the opposite of HTML

An Example:
• The while keyword, for example, must be typed “while”, not
“ While” or “ WHILE”.......

• The variables lastName and lastname, are two different variables


Rules for writing a JavaScript program :
You should follow the rules given below when writing a program using
JavaScript:
• Using a semicolon at the end of the statement is optional.

let a, b, c;
a = 5;
b = 6
c = a + b;
document.write(5 + 6);

• Using semicolon makes it possible to write multiple statements on one line.


a = 5; b = 6; c = a + b;
Rules for writing a JavaScript program :
You should follow the rules given below when writing a program using
JavaScript:
• JavaScript ignores multiple spaces. You can add white space to your
script to make it more readable.

let person = "Hege";


let person="Hege";

• A good practice is to put spaces around operators ( = + - * / ):


let x = y + z;
The Object Model in JavaScript :
• Like the most other programming languages of a generation

JavaScript is characterized by the Object Model

• This means that you think about your JavaScript program in terms of the
objects you want to work with .

• For programming purposes , the browser windows ,the HTML document,


HTML Elements, forms etc… ,are the objects which is turn and formed of
other objects such as text boxes and radio buttons .
The Object Model in JavaScript :

• You can access information about the objects with the help of methods .
• Methods are functions connected with objects.
• In other words ,the actions you can perform on or with objects are called
Method
• We will learn to use simple object and method to write programs in
JavaScript.
Object.Method()
The Object Model in JavaScript :
For any Object that has a Method:
1. Type the name of the object
2. Followed by a DOT
3. Then followed by the name of the method
4. And the set of parenthesis Object.Method()
Example:

Car . Travel ( )

Name of the object Dot Name of the Method Set of parenthesis


The Object Model in JavaScript :
• In other words Object doesn't matter for example if you have an object named Car
And you want to define a Method ,say Travel you would type :
Car.Travel()
• Let’s us study some simple codes for JavaScript:
objectName.methodName()

❖ document.write()
❖ document.writeln()
❖ document.getElementById()
❖ window.alert()
❖ window.confirm()
❖ window.prompt()
document .write() Method:
The document.write() method is used for displaying the text directly on the

current document of the browser window .

" or '

document.write("welcome to JavaScript");

Object called 'document 'which The method write() of this String or Text that you
refers to the current document of object is to display a string or text want to display on the
the browser window on the screen . browser window.
document .write() Method:
The document.write() method is used for displaying the text directly on the

browser window.

<html>
<head>
<title>Welcome</title>
</head>
<body>
<script language="JavaScript">
document.write("Welcome To JavaScript");
</script>
</body>
</html>
Welcome To JavaScript
A simple JavaScript program:
• To display a simple text on the browser windows as shown below the following
script has to be written. Write some text directly to the HTML output:
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script language="JavaScript">
document.write("Hello World!");
document.write("Welcome To JavaScript");
The two statements will
document.write('Hello World!'); appear on the same line
document.write('Welcome To JavaScript');
</script>
</body>
</html>
A simple JavaScript program:
• To display a simple text on the browser windows as shown below the following
script has to be written. Write some text directly to the HTML output using
<br> tag:
<html>
<head><title>Welcome</title></head>
<body> The two statements will appear on the
<script language="JavaScript"> different line
document.write("Hello World!");
document.write("<br>");
document.write("Welcome To JavaScript");
document.write("<br>");
document.write("Hello <br> World!");
</script>
</body>
</html>
document .write() Method:
The document.write() method is used for displaying HTML elements
directly on the browser window.

" or '

document . write(" <h2>Hello World!</h2> ");


Object called 'document
The method write() of this The HTML Element
'which refers to the current
object is to display the HTML that you want to display
document of the browser
Element on the screen . on the browser window.
window
Using HTML in JavaScript :
• HTML tags can also be included in the JavaScript code to generate HTML elements

that will be displayed in the browser window.


• Once the browser received a string from the document .write() method, the browser
accept the string includes within the parentheses and double quotation, and Treats in as
HTML code.
<html>
<head><title>Welcome</title></head>
<body>
<script language="JavaScript">

document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");


</script>
</body>
</html>
Using HTML in JavaScript :
•The string without the HTML tag is accepted as a sample text the browser three
each HTML tag accordingly :
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script language="JavaScript">
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
document.write("<h2><U>Hello World!</U></h2><p>Grade8</p>");
document.write("<B>Hello World!</B>");
document.write("<br>");
document.write("<h2>Hello <br> World!</h2>");
</script>
</body>
</html>
Using HTML in JavaScript :
• Once the browser received a string from the document .write() method, the browser accept the
string includes within the parentheses and double or( single quotation), and Treats in as HTML
code
<html>
<head><title>Welcome</title></head>
<center></center>
<body <font></font>
<script language="JavaScript"> Adding attributes
document.write ('<center>Grade8</center>');
document.write("<br>");
document.write ('<font size="6" color="red">computer science </font>');
</script>
</body>
</html> Grade8

Computer Science
document .write() Method:
The document.write() method is used for displaying date object
directly on the browser window.(without Quotation)

document. write( Date() )

Object called 'document The current


The method write() of
'which refers to the
this object is to display the date will display on
current document of the
date on the screen . the browser window.
browser window
Using Date() in JavaScript program:
. Write a date object directly to the HTML output:
<html>
<head>
<title>Welcome</title>
</head>
<body>

<script language="JavaScript">
document.write(Date());
</script>

</body>
</html>
document .writeln() Method:
The document.writeln() method is identical to the write() method, with the
addition of writing a newline after each statement.

document.writeln("welcome to JavaScript");
Object called 'document
The method write() of this String or Text that
'which refers to the current
object is to display a string or text you want to display on
document of the browser
on the screen . the browser window.
window

Note: It is only useful when writing to text documents


The <pre> tag
The <pre> tag defines preformatted text.
The text will be displayed exactly as written in the HTML source code.
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>The pre element</h1>
<pre>
Text in a pre element
is displayed in a fixed-width
font, and it preserves
both spaces and
line breaks
</pre>
</body>
Note: It is only useful when writing to text documents
</html>
document .writeln() Method:
• To display a simple text on the browser windows as shown below the following
script has to be written. Write some text directly to the HTML output:
<html>
<head> Text in a pre element is displayed in a fixed-width
<title>Welcome</title> font, and it preserves both spaces and line breaks .
</head>
<body>
<pre> Each content will
<script language="JavaScript"> appear on different
document.writeln("Hello World!"); line
document.writeln("Have a nice day!");
</script>
</pre>
</body> Hello World!
</html> Have a nice day!
Activity:
Create a web page including the following:
Write a JavaScript code for each question to show the following in
different section:
1. Display ‘Hello’ message using the heading level (h1…h7) of your choice
.It should be italic.

2. Display ‘your name’ in the center of the web page in blue. On a


separate line.

3. Display the heading ‘I'm reading JavaScript’ the in a big font size (6)
Center aligned and underlined.
The Answer Key
<html>
<head><title>Activity</title></head>
<body>
<script language="JavaScript">

document.write("<h2><i>Hello</i></h2>");

document.write('<font color="blue"><center>Sara Smith</center>


</font>');
document.write("<br>")
document.write('<font size="6"><center><u>I am learning
JavaScript</u></center></font>');
</script>
</body>
</html>
The Answer Key
<html>
<head><title>Activity</title></head>
<body>
<script language="JavaScript">
document.write("<h2><i>Hello</i></h2>");
</script>

<script language="JavaScript">
document.write('<font color="blue"><center>Sara Smith</center>
</font>');
document.write("<br>") </script>
<script language="JavaScript">
document.write('<font size="6"><center><u>I am learning
JavaScript</u></center></font>');
</script>
</body>
</html>
.
JavaScript can change HTML content using button
The button is a clickable button .The onclick event occurs when the
user clicks on an HTML element .
<button type= " " onclick= " ">value</button>

The type attribute specifies The onclick event occurs


when the user clicks on Will appear on the
the type of button.
an HTML element button
Button, submit, reset

" or ' Note: single quotes is used HTML


element
(when using JavaScript )
<html>
<body>
<h1>The button Element</h1>
<button type="button" onclick='alert("Hello world! ")'>Click Me! </button>
</body>
</html>
.
JavaScript can change HTML content using button
The button is a clickable button .The onclick event occurs when the
user clicks on an HTML element .
<button type= " " onclick= " ">value</button>
Example:
<html>
<body>
<h1>The button Element</h1>
<button type="button" onclick='alert("Hello world! ")'>Click Me! </button>
</body>
</html>

When clicking
on button
document.getElementById(" ").innerHTML:
• One of many JavaScript HTML methods is getElementById()is used to
Find an element by element id and Get the HTML content of an element
with id= " "

document.getElementById ("elementID") .innerHTML =""

Object called 'document ‘


The method sets or returns the
which refers to the current
returns an element HTML content (inner
document of the browser ID Value
with a specified value HTML) of an element.
window

Note: Any id should be unique, but:


If two or more elements with the same id exist, getElementById() returns the first
JavaScript can show or set HTML content
Get the HTML content of an element with id="demo "
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1> The Document Object </h1>
<h2> The getElementById() Method </h2>
<p id="demo"></p>
<h1> Get content of an element</h1>
<script language="JavaScript">
document.getElementById("demo").innerHTML = "Hello World";
</script>
</body>
</html>
JavaScript can change HTML content using button
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>

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

<button type="button"
onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'> Click Me! </button>

</body>
</html>
The HTML code using Comparison operators :
<html>
<head><title>Welcome</title></head>
<body>
<p id="demo"></p>
<h3>Comparison</h3>
<script language="JavaScript">
let x=5;
let y=5;
document.getElementById("demo").innerHTML=(x==y);

</script>
</body>
</html>
Adding comments to JavaScript Code:
• before you learn more about methods in JavaScript you learn how to add
comment to the JavaScript code
• JavaScript comments can be used to explain JavaScript code, and to make
it more readable.

• JavaScript comments can also be used to prevent execution, when testing


alternative code.
• There are two different types of comments in JavaScript:
•Single Line Comments:
Single line comments start with //
•Multi-line Comments:
Multi-line comments start with /* and end with */
Adding comments to JavaScript Code:
• There are two different types of comments in JavaScript:
•Single Line Comments:
<script language="JavaScript">
//Adding Date Object:

?
document.write(Date());
</script> s wi th
b e r t be gin
•Multi-line Comments: e m em m m en ta g
R c o – >
<script language="JavaScript"> H T ML e n t –
An co m m
/* < ! – –
The code below will change
in my web page:
*/
document.write(Date());
</script>
Activity:
Create a web page including the following:

1. Add a single line comment to JavaScript Code after the last line with "
"Adding Date Object "

2. Display "the current Date" on a separate line of the web page .

3. Change HTML element content (inner HTML) with id="demo" from


" Goodbye HTML " to " welcome to JavaScript " when clicking the click
here button
Answer key(2):
<html>
<head>
<title>Welcome</title>
</head>
<body>

<script language="JavaScript">
//Adding Date Object ①
document.write(Date()); ②
</script>
<p id="demo"> Goodbye HTML</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "

welcome to JavaScript "'> Click Me! </button> ③


</html>
The HTML code using Comparison operators :
<html>
<head><title>Welcome</title></head>
<body>
Using brackets for
<p id="demo"></p> organizing

<script language="JavaScript">
let x=5;
let y=5;
document.getElementById("demo").innerHTML=(x==y);

</script>
</body>
</html>
True

You might also like