JavaScript Basics JavaScript: What Is it? – A browser-based language – An object-based language...

Preview:

Citation preview

JavaScript Basics

• JavaScript: What Is it?– A browser-based language– An object-based language– No relation to Java

1

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

2

Static vs. Dynamic

• HTML is static (cannot change)• JavaScript is dynamic (can change)• JavaScript can respond to user actions

3

Why JavaScript?

• VBScript?– runs in IE Only

• PHP/Perl– Not in a browser

• JavaScript runs almost everywhere

4

What Can It do?

• Interacting with users in an Internet browser– error checking– validation

• Roll-Over Images• User Navigation Assistance • Menus• Animation

5

Tools Needed?

• Browser – Firefox, Internet Explorer, Safari, Chrome– Firefox for this class

• A Plain-Text Editor– Notepad– TextPad– BBEdit (Mac only)

6

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

7

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

8

Can You See JavaScript?

• JavaScript can be disabled in a browser• Were possible offer alternate, non-JavaScript

solutions as well

9

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

10

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!!

11

Hello World – The simple way

<html><head><title>Hello World!</title><script>alert("Hello World!");

</script></head><body> <p>Hi</p>

</body></html>

12

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

13

Exercise

• Code a JavaScript program that displays an alert message

14

Demo – Simple JavaScript

• Pause this slide and click the link below for a…

video demonstration

15

Hello World – The better way <html> <head><title>Hello World!</title>

<script>function hello(){

var msg="Hello World!";document.open();document.bgColor = "yellow";document.write(msg);document.close();

}</script>

</head><body onload="hello();">

<p>Hi</p>

</body></html> 16

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"

17

Declaring a Variable

• Var– var myName;

• 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)

18

Function

• Encapsulates some JavaScript code into a single function name

• Call the function name and all the code executes

19

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

20

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

21

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

22

Exercise

• Code a JavaScript program that calls a function when the page loads

• The function should change the background color to blue.

23

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

24

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

25

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 slide26

Multi-Line Comment Example

• Use /* to begin and */ to end comment block

/* This line does not runThis line does not run eitherNor does this line */

alert("HI"); //This line runs, however

27

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 commentthis continues the comment block This is the last HTML comment -->

28

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…var userInput = prompt("What is your name?," ");

29

Using a Default with Prompt()

30

var userInput = 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

31

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>

32

getElementById• The getElementById() function allows you to

get a reference to an HTML element and place that reference in a JavaScript variable

<script>var myParagraph =

document.getElementById("mypara");</script><p id="mypara">This is a test paragraph</p>

33

Demo – Get Element by ID

• Pause this slide and click the link below for a…

video demonstration

34

Changing HTML element Properties

• Using the script from the last slide, we can dynamically change the text color in the paragraph

var myParagraph = document.getElementById("mypara");myParagraph.style.color = "blue";

35

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.

36

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>37

CSS code vs. JavaScript code

• CSS/HTML example:<p style="color: red;">A paragraph</p>

• JavaScript/HTML example:var myPara = document.getElementById("mypara");myPara.style.color = "red";

<p id="mypara">A paragraph</p>38

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

40

Simple Function

• You have seen the simple hello() function• You can pass data to a function:

function hello(yourName){

var msg="Hello " + yourName;alert(msg);

}

hello("Steve"); //will display: Hello Steve 41

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

42

Local Variable Example

function testme(){

var myVar = "Hi There";}

testme();alert(myVar); //No value shown

43

Global Variable Example

var myVar;function testme(){

myVar = "Hi There";}

testme();alert(myVar); //Value IS shown

44

Events

• Events can be detected and used to trigger JavaScript functions

• You have seen…<body onload="someFunction()">

• Try detecting a mouse-click…

<img src='flower.jpg' onclick="someFunction()">

45

Exercise

• Code a Web page that has an image on it.• When the image is clicked, display an alert box

that displays "You Clicked?"

46

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>

47

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

48

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">

49

Demo – Using an External .JS file

• Pause this slide and click the link below for a…

video demonstration

50

The DIV tag

• You can divide your Web page into sections by using the <div> tag

• Just place some code between the <div> and </div> tags. Example…

<div id="mydiv"><p>Hi there</p>

<p>Back at ya</p></div>

51

DIV continues

• By giving a DIV an id (e.g. "mydiv") you can change properties for all HTML code in the div.

• Examplevar myDivVar = document.getElementById("mydiv");myDivVar.style.color = "blue";

• Now all the text in the DIV will be blue

52

innerHTML• The innerHTML properly allows you to change

all of the HTML and/or text between the element tags your are working with.

• Example…<p id="mypara">Hi</p>

<script>var myP = document.getElementById("mypara");myP.innerHTML = "Hello"

</script>53

innerHTML with DIV

<div id="mydiv"> <p>Hi</p> <p>There</p></div><script> var myd = document.getElementById("mydiv"); myd.innerHTML = "<p>How are you?</p>";</script>

54

Exercise

• Code a Web page with this DIV<div id="mydiv2"><p>Hi There</p><p>How are you?</p></div>

• Code a JavaScript function to change the HTML in the DIV to display a single image instead of the paragraphs.

55

End of Lesson

56

Recommended