Javascript
Javascript
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
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>
<script type="text/javascript">
var msg=prompt("Enter your names please:");
alert("Your names:" +msg);
</script>
<!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>
<!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.
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.:
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.
<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>
<!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(" ",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
<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>
<script type="text/javascript">
var i=10;
while(i>=0)
{
document.write("<br>"+i);
i--;
}
</script>
<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>
<!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>
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.
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>
<!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>
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>
<!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>
13
4. JavaScript Syntax
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>
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>
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:
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:
This starts the color string with the # symbol, which is the standard prefix for hex color codes.
3. Generate 6 random characters:
• 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;
So, for example if you call getRandomColor(), it might generate something like #A3F9D1,
which is a random hex color code.
18