JavaScript v1
JavaScript v1
Why JavaScript?
• HTML to define the
content of web pages
• CSS to specify the
layout of web pages
• JavaScript to program
the behavior of web
pages
JavaScript Can Change HTML Content
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('de
mo').innerHTML = 'Hello JavaScript!'">
Click Me!</button>
</body>
</html>
<script>
function changeImage() {
var image =
document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
JavaScript Can Change HTML Styles
(CSS)
<h1>What Can JavaScript Do?</h1>
<script>
function myFunction() {
var x =
document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
<button type="button"
onclick="myFunction()">Click
Me!</button>
JavaScript Can Validate Data
<h1>JavaScript Can Validate Input</h1>
<p>Please input a number between 1 and 10:</p>
<input id="numb" type="number">
<button type="button"
onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
<script src="myScript.js"></script>
</body>
</html>
Javascript Comments
• Single line comments start with //
//this is a comment
• Multiple line comments start with /* and end
with */
/*This is a multiple line comment so you can
drone on and on and on as much as you care
to*/
Hiding Javascripts
• Some browsers don’t understand Javascript, and display the code.
• You can use HTML comments to hide Javascripts:
• <SCRIPT LANGUAGE=“Javascript”>
<!-- Hide your script
Script
script
script
//Stop hiding now -->
</SCRIPT>
<p id="demo"></p>
<script>
var lastName = “S";
var lastname = “Satti";
document.getElementById("demo").innerHTML = lastName;
</script>
</body>
</html>
Javascript Variables
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y), or more descriptive
names (age, sum, totalVolume).
• The general rules for constructing names for variables (unique
identifiers) are:
– Names can contain letters, digits, underscores, and dollar signs.
– Names must begin with a letter
– Names can also begin with $ and _ (but we will not use it in this
tutorial)
– Names are case sensitive (y and Y are different variables)
– Reserved words (like JavaScript keywords) cannot be used as names
Defining a JavaScript Variable
• var x = 5;
var y = 6;
var z = x + y;
• var carName;
• carName = “Volvo”;
• var person = "John Doe", carName
= "Volvo", price = 200;
Re-Declaring JavaScript Variables
var carName = "Volvo"; var carName = "Volvo";
var carName; var carName = “Mehran”;
window.alert(carName); window.alert(carName);