|
Jan's Web Scripting Demo: JavascriptJavaScript is a programming language that is commonly used to write scripts for controlling what shows on a web page and for creating ways for the user to interact with the elements on the page. A statement is a single command in a script. It must be a single line of code. A function is made up of one or more statements. A function can be called or invoked in response to an action or event, like when the page loads or when the user clicks on an object. The statements in the function are executed in the order they are listed unless there are alternates based on criteria. For example, if a comparison is true (x > 0), do one thing (write the word "positive"). Otherwise do a different thing (write "negative or zero"). A script is a set of statements and functions. Any statements that are not part of a function will be executed when the browser reads the page. These usually set initial values for variables that will be used later or pre-load images. A function will not execute until it is called. This page will introduce you to some features of JavaScript, just enough to help you understand the scripts in the examples. Example: Change Image [This image is also used in Computer Basics:Lessons:Lesson 1:Computer Types To make the image change requires three parts:
<script>
//Switches image of vehicles to a different version or returns to original image var countclicks=0; //Initialize a counter when the page loads function showlabels() {countclicks=1; //Increase the counter document.getElementById("vehicles").src='vehicles-labels.gif'; //Changes the source for the image } function showvehicles() {document.getElementById("vehicles").src='vehicles.gif'; //Returned the image to the original source file countclicks=0; //Reset the counter to zero } function changeimage() //Pick which function to use {if (countclicks===0) {showlabels();} else {showvehicles();} } </script> The script above is one of many ways to accomplish the same effect. Where do you put the script?
<script>
function showtext() {document.getElementById('mytext').innerHTML="This was created by my script"; } </script>
SyntaxLike any other programming language, JavaScript is picky about the syntax of what you write. JavaScript syntax include rules about spelling, capitalization, and punctuation. If you omit a comma or a semicolon or a brace or misspell a property name, the whole process may stop dead or (even worse!) give incorrect results. Tips about JavaScript Syntax:
Writing JavaScript Statements
Writing JavaScript Functions
Calling a JavaScript FunctionA JavaScript function is called or invoked by an action like onMouseOver or onClick or by an event like onLoad or onChange. <body onLoad="myFunction()"> <p onClick="showtext()">Click here to show text</p> <div onMouseOver="replaceme()> |