600 likes | 753 Views
JavaScript Basics. JavaScript: What Is it? A browser-based language An object-based language No relation to Java. What is JavaScript?. A computer language Displaying Text Moving an Image Asking a user for information Source code Processing the code running or executing in the browser.
E N D
JavaScript Basics • JavaScript: What Is it? • A browser-based language • An object-based language • No relation to Java
What is JavaScript? • A computer language • Displaying Text • Moving an Image • Asking a user for information • Source code • Processing the code • running or executing in the browser
Static vs. Dynamic • HTML is static (cannot change) • JavaScript is dynamic (can change) • JavaScript can respond to user actions
Why JavaScript? • VBScript? • runs in IE Only • PHP/Perl • Not in a browser • JavaScript runs almost everywhere
What Can It do? • Interacting with users in an Internet browser • error checking • validation • Roll-Over Images • User Navigation Assistance • Menus • Animation
Tools Needed? • Browser • Firefox, Internet Explorer, Safari, Chrome • Firefox for this class • A Plain-Text Editor • Notepad • TextPad • BBEdit (Mac only)
The <script> Tag • JavaScript code is inserted between script tags • <script> </script> • (I use lowercase because of XHTML standards) • This is called a script block
Script Tag - Continued • This script is not shown to the user, but is code that does something • The script block can be between the <head> </head> tags or between the <body> </body> tags • Most often we will put it in the <head> area
Can You See JavaScript? • JavaScript can be disabled in a browser • Were possible offer alternate, non-JavaScript solutions as well
Not the Only Language • Technically we should tell the browser what language we are using • <script language="JavaScript"> • JavaScript is the default so I will accept the <script> tag without the language attribute
DOCTYPE • Technically, the first line in an HTML file should be the DOCTYPE • II tend to use … <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" • There are many others that enforce validation of HTML and XHTML standards • To keep things simple and easy, DOCTYPE is not required for most class assignments • In the Real World, you should use it!!
Hello World – The simple way <html> <head><title>Hello World!</title> <script> alert("Hello World!"); </script> </head> <body> <p>Hi</p> </body></html>
The alert() function • Sends the text enclosed within the ( ) to a special message (dialog) box • Controlled by the operating system, not JavaScript • It is Modal • means the program stop working until the user clicks the OK • Parsing the program stops when the alert( ) function is called
Exercise • Code a JavaScript program that displays an alert message
Demo – Simple JavaScript • Pause this slide and click the link below for a… video demonstration
Hello World – The better way <html> <head><title>Hello World!</title> <script> function hello() { varmsg="Hello World!"; document.open(); document.bgColor = "yellow"; document.write(msg); document.close(); } </script> </head> <body onload="hello();"> <p>Hi</p> </body></html>
The Document Object • document is a JavaScript object that represents the Web page • You will use this object to manipulate the appearance of a Web page using JavaScript code (e.g. document.bgColor = "yellow"
Declaring a Variable • Var • varmyName; • Reserves a variable name for your JavaScript • Scope • Variables declare outside of functions exist for all code in the Web page (e.g. they are global) • Variables declared inside functions exist just inside that function's code (e.g. they are local)
Function • Encapsulates some JavaScript code into a single function name • Call the function name and all the code executes
The Onload Event • The onload event is triggered when a Web page first opens. • It allows you to specify JavaScript code you want to run as soon as the page is fully loaded into the browser • Usually calls a JavaScript function • Ensures that all JavaScript page elements are loaded into the browser before you try to refer to them with JavaScript code
What happened to the Paragraph? • In the last "Hello World" example a paragraph was specified (i.e. <p>Hi</p>) • Why didn't we see it? • The hello() function opened a brand new page! • Document.open(); • Document.write() starts a new page automatically even if we do not explicitly open() and close() a new page
The DOT operator • references the document's functions by using a dot ( . ) • E.g. document.write(msg); • references the document's properties by using a dot ( . ) • e.g. document.bgColor = "yellow"; • "Old" style… you will learn new way later • Semicolon at the end of line • usually optional, but do i
Exercise • Code a JavaScript program that calls a function when the page loads • The function should change the background color to blue.
Browser Differences • Some browser differences for Firefox, Chrome, IE, Safari, Opera, etc. • Use Firefox for this class • Most JavaScript will work for all browsers • You can use JavaScript to detect browser versions and issue browser/version specific code
Good Coding Practices • Keep similar code in one place • Indenting • Following code indenting rules will become extremely important as the code gets more complicated • See the Best Practices link on the class Web site • Use Comments where helpful
Comments • You may comment out JavaScript code to prevent it from running (or just to make comments for documentation purposes) • Single-line comment examples (Use // ) //This is just some texts // alert("this does not run"); alert("This runs"); //This is just a comment • Multi-line comment example on next slide
Multi-Line Comment Example • Use /* to begin and */ to end comment block /* This line does not run This line does not run either Nor does this line */ alert("HI"); //This line runs, however
HTML comments vs JavaScript • If you are not in a JavaScript block… • (i.e. code between <script> and </script> ) … you must use HTML comments instead (<!-- and --> ) <!-- This is an html comment this continues the comment block This is the last HTML comment -->
Getting Input from a User • A simple way to receive information from a user into a JavaScipt variable is to use the prompt() function • Example… varuserInput = prompt("What is your name?," ");
Using a Default with Prompt() varuserInput = prompt("What is your Age?", "39");
Exercise • Write a JavaScript program to prompt a user for their first name, then display an alert box that say "Hi, firstname" • NOTE: You can combine text with a variable like so… "Hello " + myVar
Giving HTML Elements an ID • Giving your HTML element a unique ID allows JavaScript to reference the elements and dynamically change them <p id="mypara"> This is a test paragraph </p>
getElementById • The getElementById() function allows you to get a reference to an HTML element and place that reference in a JavaScript variable <script> varmyParagraph = document.getElementById("mypara"); </script> <p id="mypara"> This is a test paragraph </p>
Demo – Get Element by ID • Pause this slide and click the link below for a… video demonstration
Changing HTML element Properties • Using the script from the last slide, we can dynamically change the text color in the paragraph varmyParagraph = document.getElementById("mypara"); myParagraph.style.color = "blue";
Styles (CSS) • Styles (CSS) allow us to control many properties of an HTML element. • Examples: Text size, text color, background colors, where the element is positioned on the page, etc. • I will teach you all the CSS code you need for this class.
A little CSS • You should control the color, text size, etc. properties using Styles (i.e. CSS) • Here is a Simple Example making all the text in a paragraph blue<style> p.mystuff{ color: blue; }</style> <p class="mystuff">This should appear blue</p>
CSS code vs. JavaScript code • CSS/HTML example: <p style="color: red;">A paragraph</p> • JavaScript/HTML example: varmyPara = document.getElementById("mypara"); myPara.style.color = "red"; <p id="mypara">A paragraph</p>
Demo - Simple CSS Pause this slide and click the link below for a… video demonstration
Exercise • Code a Web page that has the following paragraph in it <p id="para2">Hello There</p> • Code a function that changes the text color of the paragraph to blue when the page loads
Simple Function • You have seen the simple hello() function • You can pass data to a function: function hello(yourName) { varmsg="Hello " + yourName; alert(msg); } hello("Steve"); //will display: Hello Steve
Variable Scope • Variables declared outside functions can be "seen" anywhere in the JavaScript code (global) • Variables declared within a function can only be "seen" within that function (local) • A global variable may be declared outside a function but have its value set within a function. That value will be "seen" everywhere in the JavaScript
Local Variable Example function testme() { varmyVar = "Hi There"; } testme(); alert(myVar); //No value shown
Global Variable Example varmyVar; function testme() { myVar = "Hi There"; } testme(); alert(myVar); //Value IS shown
Events • Events can be detected and used to trigger JavaScript functions • You have seen… <body onload="someFunction()"> • Try detecting a mouse-click… <imgsrc='flower.jpg' onclick="someFunction()">
Exercise • Code a Web page that has an image on it. • When the image is clicked, display an alert box that displays "You Clicked?"
JavaScript not Enabled? • You can specify HTML between the <noscript> and </noscript> tags to display if JavaScript will not run in a user's browser. <noscript> <p>Enable Javascript to run this page!</p> </noscript>
Accessibility • Any Web page you code that is going out to the public should take in account that users may have disabilities. Types include… • sight (including color-blindness) • hearing • motor • See • www.w3.org/WAI/ • www.section508.gov/ • www.cynthiasays.com
External JavaScript files • In the real world, it is preferable to keep your JavaScript code in a separate file and link to it in your Web page. • For class assignments, however, just leave it in the same file! • To import a file with JavaScript do… <script type="text/javascript" src="myjavascript.js">
Demo – Using an External .JS file • Pause this slide and click the link below for a… video demonstration