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

Java SCR Pit

JavaScript is a scripting language used to make web pages dynamic and interactive. It allows HTML elements to be modified, like changing text or styles. JavaScript code is inserted between <script> tags and variables, functions, and statements can be used to manipulate the DOM and trigger events. Common data types in JavaScript include strings, numbers, Booleans, null and undefined values. Popup boxes like alerts, prompts, and confirmations can be used to display and accept input from users.

Uploaded by

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

Java SCR Pit

JavaScript is a scripting language used to make web pages dynamic and interactive. It allows HTML elements to be modified, like changing text or styles. JavaScript code is inserted between <script> tags and variables, functions, and statements can be used to manipulate the DOM and trigger events. Common data types in JavaScript include strings, numbers, Booleans, null and undefined values. Popup boxes like alerts, prompts, and confirmations can be used to display and accept input from users.

Uploaded by

mekideszekarias
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Introduction to Javascript

1
.
• JavaScript is a scripting or programming language of
the web.
• JavaScript makes HTML pages more dynamic and
interactive.
The HTML <script> Tag
The HTML <script> tag is used to define a client-side
script (JavaScript).
• The <script> element either contains script
statements, or it points to an external script
file through the src attribute.
• Common uses for JavaScript are image
manipulation, form validation, and dynamic
changes of content.
• In HTML, JavaScript code is inserted
between <script> and </script> tags
HTML to define the content of web pages.
CSS to specify the layout of web pages
JavaScript to program the behavior of web pages

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo">Hello world</p>
<script>
document.getElementById("demo").innerHTML = "My
First JavaScript";
</script>

</body>
</html>
<h2>JavaScript in Body</h2>
<p id="demo">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Click
me to change text above">
<script>
function ChangeText(){
document.getElementById("demo").innerHTML = "My First
JavaScript";
}
</script>
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into an HTML output docment.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
Writing Into H T M L Output

Using document.write()
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
document.write("<h1> Hello, world!</h1>");
</script>
</body>
</html>
Using innerHTML
⚫ To access an HTML element from JavaScript, you can use the
document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property
defines the HTML content:
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

7
Using window.alert()
we can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword.
Using console.log()
<!DOCTYPE html>
<html>
<body>
<h2>Activate Debugging</h2>

<p>F12 on your keyboard will activate debugging.</p>


<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>

<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Statements
⚫ JavaScript statements are "commands" to the browser.
⚫ The purpose of the statements is to tell the browser what to do.

<html>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

<div id="myDIV">A DIV.</div>


<script type=“text/javascript” >

document.getElementById("demo").innerHTML="Hello Dolly";

document.getElementById("myDIV").innerHTML="How are you?";

</script>

</body>

</html>
10
JavaScript is Case Sensitive
⚫A function getElementById is not the same as
getElementbyID.
⚫ A variable named myVariable is not the same as
MyVariable.
White Space
⚫ JavaScript ignores extra spaces.You can add white
space to your script to make it more
readable.The following lines are equivalent:
⚫ var person="Hege";
⚫ var person = "Hege";

11
JavaScript Comments.
⚫ Comments will not be executed by JavaScript.
⚫ Comments can be added to explain the JavaScript, or to
make the code more readable.
⚫ Single line comments start with //.
⚫ Multi line comments start with /* and end with */.
⚫ Example
//Write to a heading:
document.getElementById("myH1").innerHTML="Welc ome
to my Homepage";
/* The code below will write to a heading and to a paragraph,
and will represent the start of my homepage: */
document.getElementById("myH1").innerHTML="Welc ome to
my Homepage";

12
How to Change HTML Elements
⚫ HTML elements are changed using JavaScript, the
HTML D O M and events.
⚫ Eg. C hange the Background Color
<html>
<body>
<script type="text/javaScript">
document.body.bgColor="yellow";
</script>
<p>The background color was changed by the
script.</p>
</body>
</html>

13
Changing the Text HTML Element
⚫ The easiest way to get or modify the content of an
element is by using the innerHTML property
<html>
<body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="New
text!";
</script>
<p>The paragraph above was changed by the
script.</p>
</body>
</html>

14
Using function
<html>
<head>
<script type="text/javascript">
function ChangeText(){
document.getElementById("p1").innerHTML="New text!";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Click
me to change text above">
</body>
</html>

15
Using the Style O bject
➢ The Style object represents of each HTML element
represents its individual style.
<html>
<head>
<script type="text/javascript">
function ChangeText() {
document.getElementById("p1").style.color="blue";
document.getElementById("p1").style.fontFamily="Arial";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Click me to
change text above">
</body>
</html>
16
JavaScript Variables
⚫You declare JavaScript variables with the var keyword:
var carname;
⚫ JavaScript variables are "containers" for storing information:
<html>
<body>
<script type=“text/javascript”> var x=5;
var y=6; var z=x+y;
document.write(x + "<br>");
document.write(y + "<br>");
document.write(z + "<br>");
</script>
</body>
</html>

17
Cont---
⚫ Variable can have short names (like x and y) or more
descriptive names (age,sum, totalvolume).
⚫ Variable names must begin with a letter
⚫ Variable names can also begin with $ and _ (but we will
not use it)
⚫ Variable names are case sensitive (y and Y are different
variables)
Legal variable names in JavaScript
_ May only consist of letters, digits, and underscores
_ Can not have blank spaces
_ May not begin with a number
_ May not be a JavaScript reserved word (keyword)

18
JavaScript D ata Types

There are just three simple data types:


– string,
– numeric,and
– Boolean.

19
String D ata Type
● A string literal is a sequence of characters
delimited by single or double quotes: "This is
a string" 'But this is also a string'.
var string_value = "This is the first line\n This is
the second line";
● to include a quote within the quoted string,
– Use a single and double quotes can be used
interchangeably
var string_value = "This is a 'string' with a quote." or:
var string_value = 'This is a "string" with a quote.'

20
Number Data Type
● Numbers in JavaScript are floating-point numbers,
●All of the following are valid floating-point numbers:
0.3555 ,144.006 ,-2.3 ,19.5e-2 (which is equivalent to
19.5-2)
● octal and hexadecimal notation can be used
–A hexadecimal number begins with a zero, followed
by an x:
0xCCFF
–Octal values begin with zeros, and there is no leading
x:
0526

21
Null and Undefined
● Not declared
–alert(sValue); //results in JavaScript error because
sValue is not declared first
● A null variable is one that has been defined, but hasn't
been assigned a value.
– var sValue;
–alert(sValue); //no error, and a window with
the word 'undefined' is opened
● If the variable has been declared but not initialized, it is
considered undefined
Constants
● const CURRENT_MONTH = 3.5;

22
Example
<html>
<body>
<script type=“text/javaScript”>
var person;
var car="Volvo";
document.write(person + "<br>");
document.write(car + "<br>");
var car=null
document.write(car + "<br>");
</script>
</body>
</html>
23
JavaScript Popup Boxes
➢ three kinds of popup boxes:Alert box, Confirm box,
and Prompt box.
– Alert Box
● Used if you want to make sure information comes
through to the user.
alert("sometext");
– Confirm Box
● used if you want the user to verify or accept
something.
confirm("sometext");
– Prompt Box
●used if you want the user to input a value before
entering a page.
prompt("sometext","defaultvalue");
24
Example Alert box
<html>
<head>
<script type="text/javascript">
function disp_alert() {
alert("I am an alert box!!");
}
</script>
</head>
<body>
<input type="button"
onclick="disp_alert()"value="Display alert box" />
</body>
</html>

25
Example Confirm Box
html>
<head>
<script type="text/javascript">
function disp_confirm() {
var r=confirm("Press a button");
if (r==true) {
document.write("You pressed OK!");
}
else {
document.write("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_confirm()"value="Display a
confirm box" />
</body>
</html> 22
Example prompt box
<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name", "Harry Potter");
if (name!=null && name!="") {
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
</body>
<input type="button" onclick="disp_prompt()"
value="Display a prompt box" />
</body>
</html>

27
Operators and Statements
● Assignment
➢ NValue = 35.00;
➢ nValue = nValue + 35.00;
➢nValue = someFunction( );//function call
➢var firstName = lastName = middleName = ""; //more than
one assignment is possible
– Arithmetic Statements
C o ncatenation ( “+” used with string)
var newString = "This is an old " + oldString;
Multiplication ( “*” used with numbers)
var newValue = 3.5 * 2.0; //result is 7
var newValue = 3.5 * "2.0"; //result is still 7
var newValue = "3.5" * "2.0"; // still 7 28
Cont---
Since + is used as a concatenation with string.
var newValue = 3.5 + " 2.0"; // result is 3.52.0
● Better way to use is by explicitly converting the

value
var aVar = 3.5 + parseFloat("2.3 the sum is ");
document.write(aVar); //result is 5.8
⚫ The Unary Operators
++ Increments a value
-- Decrements a value
- Represents a negative value

29
● Ternary Operator
condition ? value if true; value if false;
● Logical Operators
– A N D (&&) ,OR (||) ,N OT(!)

Conditional Statements and Program Flow


– if
– if...else
– Switch

30
If Statement
➢ Use the if statement to execute some code
only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
➢ Note that if is written in lowercase letters.
Using uppercase letters (IF) will generate a
JavaScript error!

31
example
<html>
<body>
<p>Click the button to get a "Good day" greeting if the time is less than 20:00.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var x=5;
var y=4;
var z=x*y
if (z<20)
{
z="Good day";
}
document.getElementById("demo").innerHTML=z;
}
</script>
</body>
</html>
32
If...else Statement
⚫ Use the if....else statement to execute some
code if a condition is true and another code if
the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

33
Example
<html>
<body>
<p>Click the button to get a time-based greeting.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type="text/javaScript">
function myFunction()
{
var x=4; var y=7; var z=x*y;
if (z<20)
{ z="Good day"; } else
{ z="Good evening"; }
document.getElementById("demo").innerHTML=z;
}
</script>
</body>
</html>

34
If...else if...else Statement
⚫ Use the if....else if...else statement to select one of
several blocks of code to be executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor
condition2 is true
}
35
JavaScript Switch Statements
⚫ Use the switch statement to select one of many
blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
36
Example
<html>
<body>
<p>Click the button to display what day it is today.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{ var x;
var d=new D ate().getDay();
switch (d)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break; 33
Cont--
case 2:
x="Today it's Tuesday"; break;
case 3:
x="Today it's Wednesday";
break; case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday"; break;
case 6:
x="Today it's Saturday"; break;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>

34
The Loops
➢ While
➢ do...while
➢ For ( two types )
– First type
For (initial value; condition; update)
{… }
– second type of the for loop is a for...in loop
● which accesses each element of the array as a separate
item.The syntax for this handy statement is:
for (variable in object) {
...
}

39
The For Loop
⚫ The for loop is often the tool you will use when you
want to create a loop.
⚫The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
{
the code block to be executed
}

⚫ Statement 1 is executed before the loop (the code


block) starts.
⚫ Statement 2 defines the condition for running the
loop (the code block).
⚫ Statement 3 is executed each time after the loop
(the code block) has been executed.

40
Example
<html>
<body>

<p>Click the button to loop through a block of code five times.</p>


<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html> 37
The For/In Loop
⚫The JavaScript for/in statement loops through the properties of an object:
Example
<html><body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{txt=txt + person[x];}
document.getElementById("demo").innerHTML=txt;
}</script>
</body>
</html>
42
Example 2 for in loop
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = " B M W " ;
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html

43
The While Loop

⚫ The while loop loops through a block of


code as long as a specified condition is
true.
⚫ Syntax
while (condition)
{
code block to be executed
}

44
Example
<html>
<body>
<p>Click the button to loop through a block of as long as <em>i</em> is less than
5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var x="",i=0;
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html> 45
The Do/While Loop
⚫ The do/while loop is a variant of the while
loop.This loop will execute the code block
once,before checking if the condition is
true,then it will repeat the loop as long as
the condition is true.
⚫Syntax
do
{
code block to be executed
}
while (condition);
46
Example
<html>
<body>
<p>Click the button to loop through a block of as long as <em>i</em> is less than
5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script type=“text/javaScript”>
function myFunction()
{
var x="",i=0;
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5) ;
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
43
</html>
JavaScript A rrays
⚫ An array defined as number of memory locations,
each of which can store the same data type and
which can be references through the same
variable name.
⚫ An array is a collective name given to a group of
similar quantities.
⚫The following code creates an Array called cars:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
or (condensed array):
var cars=new Array("Saab","Volvo","BMW");
or (literal array):
48
Example
<html>
<body>
<script type=“text/javaScript”>
var i;
var cars = new Array();
cars[0] = "Saab";
cars[1] = "Volvo";
cars[2] = "BMW";
for (i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
</script>
</body>
</html>
49
An
<html>
array to write a weekday
<body>
<script type="text/javascript">
var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today it is " + weekday[d.getDay()]);
</script>
</body>
</html>
50
JavaScript Objects
⚫ An object is delimited by curly braces. Inside the
braces the object's properties are defined as
name and value pairs (name :value).The
properties are separated by commas:
var person={firstname:"John", lastname:"Doe",
id:5566};
The object (person) in the example above has 3
properties: firstname, lastname, and id.
Spaces and line breaks are not important.Your
declaration can span multiple lines:
var person={
firstname :"John",
lastname :"Doe",
id : 5566
};
47
Example
<html>
<body>
<script type=“text/javaScript”>
var person={
firstname : "John",
lastname : "Doe",
id : 5566
};
document.write(person.lastname + "<br>");
document.write(person["lastname"] + "<br>");
</script>
</body>
</html>
52
JavaScript Form Validation
⚫ JavaScript can be used to validate data in
HTML forms before sending off the
content to a server.
Form data that typically are checked by a
JavaScript could be:
◦ has the user left required fields empty?
◦ has the user entered a valid e-mail address?
◦ has the user entered a valid date?
◦ has the user entered text in a numeric field?

53
example
<html>
<head>
<script type="text/javascript">
//Form validation code will come here.
function validate()
{
if( document.Form1.username.value == "" )
{
alert( "Please provide your username!" );
document.Form1.username.focus() ;
return false;
}
if( document.Form1.password.value == "" )
{
alert( "Please provide your password!" );
document.Form1.password.focus() ;
return false;
}
}
</script>
</head>

54
cont…
<body >

<form action="formvalidate.php" method='post' name="Form1"


onsubmit="return(validate())"; >
<fieldset>
<legend> <b>Login form</b></legend>
User Name:
<input type="text" name="username" maxlength="50"
size="25"><BR><br>
Password:
<input type="password" name="password" maxlength="50"
size="25"><br/>
<input type='submit' value="login" /><input type='reset' value='Reset' />
</fieldset>
</form>
</body>
</html>

55
Email validation
<html>
<head>
<script type="text/javaScript">
function validateForm()
{
var x=document.myForm.email.value; var y=document.myForm.pass.value;
var atpos=x.indexOf("@ ");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address"); document.myForm.email.focus(); return false;
}
if(y=="")
{
alert("please provided your passwerd"); document.myForm.pass.focus();
return false;
}
}
</script>

52
Cont..
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm();" method="post">
<fieldset>
<legend>signin</legend>
&nbsp;&nbsp;Email:&nbsp;&nbsp;<input type="text"
name="email"><br/>
password: <input type="password"
name="pass"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>

57
HTML Audio - Using <embed>
⚫ The <embed> tag defines a container for external
(non-HTML) content.
Example
<html>
<body>
<embed height="50" width="100“
src="mami.mp3">
<p>If you cannot hear the sound,your computer or
browser doesn't support the sound format.</p>
<p>Or, you have your speakers turned off :)</p>

</body>
</html>

58
Example 2
<html>
<body>
<audio controls>
<source src="mami.mp3" type="audio/mpeg">
<source src="mami.ogg" type="audio/ogg">
Your browser does not support this audio
format.
</audio>
</body>
</html>
59
HTML Video - Using <embed>
⚫ The <embed> tag defines a container for
external (non-HTML) content.
Example
<html>
<body>
<h2>Playing the Object</h2>
<embed src=“cc.swf" width="200"
height="200"><p>If you cannot see this, your
computer doesn't support the format</p>
</body>
</html>
60
HTML Video - Using <object>

⚫ The <object> tag tag can also define a


container for external (non-HTML)
content.
Example
<html>
<body>
<object height="200" width="200"
data=“cc.swf"></object>
</body>
</html>

61
Example 2
<html>
<body>
<video width="320" height="240" controls autoplay>
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
<object data="movie.mp4" width="320"
height="240">
<embed width="320" height="240"
src="movie.swf">
</object>
</video>
</body>
</html>
62
<!DOCTYPE html>
<html lang="en">

<head>
<title>Toggle Password Visibility</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-
icons@1.3.0/font/bootstrap-icons.css" />
<link rel="stylesheet" href="css/style.css" />
</head>

<body>
<div class="container">
<h1>Sign In</h1>
<form method="post">
<p>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" />
<i class="bi bi-eye-slash" id="togglePassword"></i>
</p>
<button type="submit" id="submit" class="submit">Log In</button>
</form>
</div>
<script>
const togglePassword = document.querySelector("#togglePassword");
const password = document.querySelector("#password");

togglePassword.addEventListener("click", function () {
// toggle the type attribute
const type = password.getAttribute("type") === "password" ? "text" :
"password";
password.setAttribute("type", type);

// toggle the icon


this.classList.toggle("bi-eye");
});

// prevent form submit


const form = document.querySelector("form");
form.addEventListener('submit', function (e) {
e.preventDefault();
});
</script>
</body>
</html>
THANK YOU
THE END
‫تمت‬
65

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy