Intro To Javascript 1
Intro To Javascript 1
• JavaScript is case-sensitive?
What can JavaScript Do?
– JavaScript can dynamically modify an HTML page
– JavaScript can react to user input
– JavaScript can validate user input
Pros and Cons of JavaScript
• Pros:
– Allows more dynamic HTML pages, even
complete web applications
• Cons:
– Requires a JavaScript-enabled browser
– Requires a client who trusts the server enough
to run the code the server provides
Using JavaScript in your HTML
• Javascript like css can be incorporated to
HTML in 3 different ways
1. Inline
2. Internally
3. Externally
Using JavaScript in your HTML
• In HTML, JavaScript code must be inserted
between the <script> and </script> tag
Where to Put your Scripts
• You can have any number of scripts
•
• Scripts can be placed in the HEAD or in the BODY
– In the HEAD, scripts are run before the page is displayed
– In the BODY, scripts are run as the page is displayed
<!DOCTYPE html>
<html><head>
<script>
function myFunction( ) {
document.getElementById(“para1").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id=“para1">A Paragraph</p>
<button type="button" onclick="myFunction( )">Try it</button>
</body>
</html>
JavaScript in <body> Example
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="para1">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction( ) {
document.getElementById("para1").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
• NB: Placing scripts at the bottom of the
<body> element improves the display speed,
because script compilation slows down the
display.
External Scripts
• Scripts can also be loaded from an external file.
• This is useful if you have a complicated script or
set of subroutines that are used in several different
documents
• External scripts are practical when the same code
is used in many different web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script
file in the src (source) attribute of a <script> tag:
External Scripts Example
• You can place an external script reference in
<head> or <body> as you like.
• The script will behave as if it was located
exactly where the <script> tag is located.
• <script src="myScript.js"></script>
• <script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External JavaScript Advantages