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

Javascript

The document provides an overview of JavaScript programming as part of a web programming course. It covers the importance of JavaScript, its capabilities, syntax, and practical examples of how to use it in web pages. Additionally, it includes exercises and code snippets to illustrate various JavaScript functions and techniques.

Uploaded by

nyampamebernard
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)
11 views

Javascript

The document provides an overview of JavaScript programming as part of a web programming course. It covers the importance of JavaScript, its capabilities, syntax, and practical examples of how to use it in web pages. Additionally, it includes exercises and code snippets to illustrate various JavaScript functions and techniques.

Uploaded by

nyampamebernard
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/ 19

WEB PROGRAMMING (CSC2248)

Unit 1: Client-side technologies (Part 3:


Javascript Programming)

Combinations: MCsE & PCsE


Year 2, Semester 2
2024-2025 academic year
Module Facilitation Team:
1. Dr Mathias NDUWINGOMA
MARCH 24, 2025
2. Albert NGIRUWONSANGA
UR-CE
March 24, 2025
UR-CE
Table of Contents
1. Why Study JavaScript? .............................................................................................................................. 9
JavaScript is one of the 3 languages all web developers must learn: ........................................................ 9
1. HTML to define the content of web pages ........................................................................................... 9
2. CSS to specify the layout of web pages ................................................................................................ 9
3. JavaScript to program the behavior of web pages ................................................................................ 9
2. What can JavaScript do? ......................................................................................................................... 10
2.1. JavaScript can change HTML content .............................................................................................. 10
3. Where to Insert JavaScript ...................................................................................................................... 11
3.1. JavaScript in <head> ........................................................................................................................ 11
3.2. JavaScript in <body> ........................................................................................................................ 12
3.3. JavaScript in an external file ............................................................................................................ 12
3.5. JavaScript in an external folder ........................................................................................................ 13
4. JavaScript Syntax ..................................................................................................................................... 14
4.1. JavaScript Comments ....................................................................................................................... 14
4.3. JavaScript Operators ........................................................................................................................ 15
4.4. JavaScript Keywords......................................................................................................................... 15

1
What is JavaScript?

JavaScript is a scripting language that’s used to turn web pages into applications. JavaScript can
be incorporated into web pages in a number of ways. It is used to manipulate the contents of a web
page or to allow users to interact with web pages without reloading the page.

Variables in JavaScript

Variable names must conform to the following rules:


- Variable names can include only letters, numbers, and the underscore _ or dollar sign $
character.
- Variable names cannot start with a number.
- You cannot use any reserved words as a variable name. Reserved words are words that
have a specific meaning for the JavaScript interpreter. For example, naming a variable
named var won’t work.
- As a matter of style, JavaScript variables begin with a lowercase letter. If a variable name
contains multiple words, usually an underscore is used to join the two words, or the first
letter of the second word is uppercase. So, you would write my_variable or myVariable.

Example 1:

<html>
<head>
<title>Using Javascript</title>
</head>
<body>
<script type="text/javascript">
var msg="Hello Javascript";
document.write(msg);
</script>
</body>
</html>

Example 2: Reading your names using an input box and displaying it on a page
<html>
<head>

2
<title>Using Javascript</title>
</head>
<body>
<script type="text/javascript">
var msg=prompt("Enter your names please:");
document.write(msg);
</script>
</body>
</html>

Example 3: Displaying your names in a msg box

<script type="text/javascript">
var msg=prompt("Enter your names please:");
alert("Your names:" +msg);
</script>

Example 4: Using while loop

<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<script type="text/javascript">
var i=prompt("Enter the initial value");
while (i<=10){
document.write("<br>",i);
i++;
}
</script>
<body>

</body>
</html>

Example 5: Using do while loop

<!DOCTYPE html>
<html>
<head>

3
<title>Javascript</title>
<script type="text/javascript">
var i=prompt("Enter the initial value");
do{
document.write("<br>",i);
i++;
}
while (i<=10)
</script>
<body>

</body>
</html>

Exercise:
Re-write the example 5 using for loop.
Figure 1 highlights some JavaScript reserved words which should not be used as variable names.

Figure 1: List of JavaScript reserved words

4
Using JavaScript in Your Pages

Now that you have some understanding of what JavaScript is all about, you’re ready to look at
some practical applications of JavaScript. i.e.:

• Validate the contents of a form

We can now use JavaScript to validate “registration.html” such that the form has two required
fields: reg number and age. The validation function is responsible for checking that they each
contain a value.

Edited codes for “registration.html” form should look like the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Form validation</title>
<script type="text/javascript">
function checkform() {
if(!rn.value){
alert('Reg number must contain a value!');
return false;
}
if(!age.value){
alert('Age should not be empty!');
return false;
}
}
</script>
</head>
<body>

5
<form method="post" onsubmit="return checkform()">
<table><tr><td>Reg number</td>
<td><input type="text" name="nr" id="rn"></td></tr>
<tr><td>Family name</td><td><input type="text" name="fname"></td></tr>
<tr><td>First name</td><td><input type="text" name="name"></td></tr>
<tr><td>Age</td><td><input type="text" name="age" id="age"></td></tr>
<tr><td></td><td><input type="submit" value="Save"></td></tr></table>
</form>
</body>
</html>

NB:
1) Additional codes are highlighted/in bold.
2) The expression in the if statement evaluates the value of the form field in a Boolean
context. So, if the field’s value is null or an empty string, the expression will be false. In
that case, the function displays an error message and prevents the form from being
submitted.

Example 6: Use of getElementById( )

<script>
function displaynames()
{
var names=document.getElementById("ok").value;
document.write("<font color=green size=34>"+names);
}
</script>
<form>
Please enter your names<input type="text" name="nam" id="ok">
<input type="submit" value="Display" onclick="return displaynames()">
</form>

6
Example 7: Use of getElementById( ) and perform calculation

<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<script type="text/javascript">
function op(){
var a=document.getElementById("name").value;
var c=a*6;
document.write(c);
}
</script>
</head>
<body>
<form>
<input type="text" name="fname" id="name">
<input type="submit" name="submit" value="Calculate" onclick="return op()">
</form>
</body>
</html>

Example 8: Displaying a Block of numbers

<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
<script type="text/javascript">
var b=prompt("Enter the last value");
for(var i=1;i<=b;i++){
for(var j=1;j<=b;j++)
{
document.write("&nbsp;",i*j);
}
document.write("<br>")
}
</script>
<body>
</body>
</html>

7
Note that:
• i represents rows and j represents columns.
• You can provide value 10 for the input box and check the generated blocks of numbers

Example 9: Square of a number

<script type="text/javascript">
function square( )
{
var num=document.getElementById("number").value;
alert(num*num);
}
</script>
<form>
Enter a number <input type="text" id="number" name="ber"><br>
<input type="button" value="Square" onclick="return square()">
</form>

Example 10: Use of while loop with decrement

<script type="text/javascript">
var i=10;
while(i>=0)
{
document.write("<br>"+i);
i--;
}
</script>

Example 11: Use of for loop with decrement

It is quite possible to apply font formatting on output to be displayed by document.write ( )


function. i.e.

<script>
for(var x=10;x>=0;x--)
{
document.write("<br><font face=Algerian size=12 color=blue><center>",+x);
}
</script>

8
Example 12: Using JavaScript to generate a pdf file from a web page content
<!DOCTYPE html>
<html>
<head>
<title>Layout</title>
<script type="text/javascript">
function printwindow()
{
window.print();
}
</script>
</head>
<body>

<button name="print" onclick="printwindow()">Print this</button>


</body>
</html>

Understanding JavaScript basics

Let us now, have a look on some basics of JavaScript programming.

• JavaScript is the world's most popular programming language.


• JavaScript is the programming language of the Web.
• JavaScript is easy to learn.

1. 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 Example 13:

<!DOCTYPE html>
<html>
<body>

9
<h2>My First JavaScript</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>

2. What can JavaScript do?

2.1. JavaScript can change HTML content


<!DOCTYPE html>
<html>
<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>

2.2. JavaScript can change HTML attribute values


<!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="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>

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

<button onclick="document.getElementById('myImage').src='pic_bulboff.jpeg'">Turn off the


light</button>
</body>
</html>

10
Note: Go to eLearning platform at https://elearning4.ur.ac.rw/course/view.php?id=35482 to
download 2 images required to run this program.

2.3. JavaScript can change the style of an HTML element


<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>

3. Where to Insert JavaScript


1. JavaScript in <head>
2. JavaScript in <body>
3. JavaScript in an external file
4. JavaScript in an external url
5. JavaScript in an external folder

3.1. JavaScript in <head>


<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

11
3.2. JavaScript in <body>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>

3.3. JavaScript in an external file


Codes for HTML file (jsfile.html):

<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo"></p>
<button type="button" onclick="myfunction()">Click Me!</button>
<script src="myscript.js"></script>
</body>
</html>

Codes for myscript.js file

// Define the function 'myfunction'


function myfunction() {
document.getElementById("demo").innerHTML = "Hello, you clicked the button!";
}

12
3.4. JavaScript in an external url
<!DOCTYPE html>
<html>
<body>

<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 "myScript.js")</p>
<script src="https://www.w3schools.com/js/myScript.js"></script>
</body>
</html>

3.5. JavaScript in an external folder


Codes for HTML file (jsexample.html)

<!DOCTYPE html>
<html>
<body>
<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 "myScript.js")</p>
<script src="js/myscript.js"></script>
</body>
</html>

Codes for JavaScript file (myscript.js) which is stored in js folder

// Define the function 'myfunction'


function myfunction() {
document.getElementById("demo").innerHTML = "Hello, you clicked the button!";
}

13
4. JavaScript Syntax

4.1. JavaScript Comments


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comments are NOT Executed</h2>
<p id="demo"></p>
<script>
var x;
x = 5;
// x = 6; It won't be executed
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

4.2. JavaScript variables


<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x is defined as a variable.
Then, x is assigned the value of 6:</p>
<p id="demo"></p>
<script>
var x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

14
4.3. JavaScript Operators
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Operators</h2>
<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>
</body>
</html>

4.4. JavaScript Keywords


<!DOCTYPE html>
<html>
<body>
<h2>The var Keyword Creates Variables</h2>
<p id="demo"></p>
<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>
</body>
</html>

Finally, let us try this JavaScript Example that changes text colour by click a button:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Webpage</title>
<style>
body {
15
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
background-color: #f0f0f0;
color: #333;
}

h1 {
color: #007bff;
text-decoration: underline;
}

p{
font-size: 16px;
line-height: 1.5;
}

.highlight {
background-color: #ffff00;
font-weight: bold;
}

#changeColorBtn {
padding: 10px;
margin-top: 15px;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Welcome to My Interactive Webpage!</h1>
<p>This is a simple webpage demonstrating the use of HTML, CSS, and JavaScript.</p>

<p>You can <span class="highlight">highlight</span> specific text.</p>

<button id="changeColorBtn">Change Text Color</button>

16
<script>
// JavaScript for dynamic behavior
document.getElementById('changeColorBtn').addEventListener('click', function() {
document.body.style.color = getRandomColor();
});

function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>

The JavaScript function getRandomColor() generates a random hex color code. The following is
a breakdown of how it works:

1. Define the set of characters:

const letters = '0123456789ABCDEF';

This string contains all possible characters that can be used in a hex color code. A hex color is
made up of six characters, and each character can be one of the 16 values represented by these
characters (0-9 and A-F).
2. Initialize the color variable:

let color = '#';

This starts the color string with the # symbol, which is the standard prefix for hex color codes.
3. Generate 6 random characters:

for (let i = 0; i < 6; i++) {


color += letters[Math.floor(Math.random() * 16)];
}

• The loop runs six times (as hex colors are 6 characters long).
• In each iteration, the code picks a random index (from 0 to 15) from the letters string.

17
• Math.random() generates a random decimal between 0 (inclusive) and 1 (exclusive).
This function Math.random() returns a floating-point number greater than or equal to 0
and less than 1. It can return values like 0.234, 0.783, 0.999, etc., but never exactly 1.
and Math.floor() rounds it down to the nearest whole number between 0 and 15.
• letters[Math.floor(Math.random() * 16)] then selects a random character from letters
based on the calculated index.
• This character is added to the color string.
4. Return the final color:

return color;

The function returns the color variable at the end.

So, for example if you call getRandomColor(), it might generate something like #A3F9D1,
which is a random hex color code.

18

You might also like