JavaScript - Texas A&M University
JavaScript
NEED MORE ON WRITING TO THE DOM
Introducing JavaScript
• is an interpreted programming language that is embedded in a web browser
• IS NOT JAVA!!!
• two ways to accomplish Java Scripting
o inline scripting, place code INSIDE the HTML code
o much like an external style sheet in design, file outside of HTML contains JAVASCRIPT code
▪ will focus on this
▪ allows us to use in MANY HTML files
▪ avoids conflicts with other languages such as XML, etc…
• does not read or write files
Where is it used?
• Client-side script for web development
• Embedded into HTML
• Can also be used as a full-fledged programming language
What's special/different about this language?
• Default support on all major browsers as it is widely used
• Handles the page behavior, compared to the look which is handled by HTML/CSS
• Provides different frameworks like jQuery (makes JS easy), AngularJS (for data-heavy sites), Node.js (for server-side development)
What documented support is available?
• Widely used so lots of documentation material can be found online. Major documentations are:
•
•
• Cheat sheet -
Best features of the language?
• Light weight and simple to use
• Universal support with lots of documentation
• Object-based and functional programming language
Including JavaScript in HTML
• placed in the section
• needs both opening and closing tag
|Inline Java Scripting |External Java Scripting |
| | |
| | |
Your first JavaScript Program embedded in HTML “Hello World”
• There are several things we must complete before we can get this to work
o create the HTML code that will include the JavaScript
o create the JavaScript code
|Hello World Example |
|HTML Code |Javascript code |
| | |
| | |
| Hello World |alert("Hello World"); |
| |// that’s it, literally!!! |
| | |
| | |
| | |
|Stuff | |
| | |
| | |
• alert is a default JavaScript function
o makes an alert box appear on the screen
1. Create the file “JavaScript.html” that will run the JavaScript code in file helloworld.js. Show me when done.
2. Place any HTML code you want within the HTML
Syntax Rules
• all default function described in JavaScript are lower case AND case sensitive
• all command in JavaScript are case sensitive
Use of Comments in JavaScript
• commenting your code
o like C/C++
o PLEASE USE!!!
o easy to use in JavaScript than in HTML
|Use of Comments |
|// |/* … code … */ |
|// Mr. Lupoli |/* |
|// Project 1 |Mr. Lupoli |
|// 6/22/03 |Project 1 |
|// Period 1 |6/23/03 |
| |Period 1 |
|// ( “//”reserves whole line for a // comment |*/ |
| | |
| |/* |
| | |
|// used for ONE line comments |“ /* ” reserves whole block until you end it with a “ */ “ |
| | |
| |used for MULTIPLE lined comments |
| |*/ |
Reserved Words
• case sensitive
• can not be used as variable or function names
• ex
|abstract |Default |float |long |super |while |
|boolean |Delete |for |native |switch |with |
|break |Do |function |new |synchronized |true |
|byte |Double |goto |null |this | |
|case |Else |if |package |throw | |
|catch |Enum |implements |private |throws | |
|char |Export |import |protected |transient | |
|class |Extends |in |public |Try | |
|const |False |instanceof |return |typeof | |
|continue |Final |int |short |Var | |
|debugger |Finally |interface |static |void | |
Variables
• kinda weird
• use var to declare ANY type of variable
o called loosely typed
• may or may not have to initialize the variable
// create a variable and assign a string to it
var message = "My First JavaScript Variable";
// display the value stored in the variable
alert( message );
Copy the code below and run
|// initialize a number variable |[pic] |
|var a = 0.06; | |
|// initialize a string variable | |
|var b = "JavaScript in easy steps"; | |
|// initialize a boolean variable | |
|var c = false; | |
|// display the data types of each variable | |
|alert( typeof a + "\n" + typeof b + "\n" + typeof c ); | |
• we can use the typeof keyword to determine actual type for that value
• “+” concatenates the string together
• “\n” makes the output display on the NEXT line
o called a new line character
• global variables
o declared in the JavaScript as usual, but not inside a function (described below)
JavaScript Common Windows
• there are many types of windows that can POP out to the user
• alert
o seen already
• confirmation box
o confirms a choice
• prompt box
o user can enter a string of some sort
o returns a value back into the .js file
|Common JavaScript Windows |
|Alert |Confirmation box |Prompt box |
|[pic] |[pic] |[pic] |
|Window Examples.js |
|alert("Mr. L is da bomb"); |
|confirm("Do you think so??"); |
|comment=prompt("What do you think of him??", ""); |
Converting Strings to Numbers
There will be many times were the input interface will treat whatever the user types in as a String, we can then transform that input into the format intended.
var x = “23”;
int real_number; // “x” is a STRING 23
realnumber = parseInt(x); // now “realnumber” is actually an INT value 23
|Type Name |Method for conversion |
|Byte |parseByte(String_to_convert) |
|Short |parseShort(String_to_convert) |
|Int |parseInt(String_to_convert) |
|Long |parseLong(String_to_convert) |
|Float |parseFloat(String_to_convert) |
Create the code to accept 3 numeric values (3 different prompts) from a user and display the total value. (It won’t work without converting!!)
literal escape constants/command constants
• used with displaying
|JavaScript Escape Sequences |
|\b – backspace |\t – tab |
|\a – audible alert |\v – vertical tab |
|\f – form feed |\\ – single backslash character |
|\n – new line |\” – double quote |
|\r – carriage return |\? – question mark |
Inspecting you code
• in Chrome
• Used to do many different things
o Code inspection (duh)
o HTML Element inspection
o Console log (actually console.log coding wise)
o Breakpoints
Breakpoints
• Same as you have used before
• Here are the steps required for setting breakpoints:
1. Open your HTML page
2. Press Ctrl+Shift+I
3. Click "Sources"
4. Open your JS file from the side pane
5. Click on a line number to set a breakpoint
6. Refresh the page to re-run the javascript
| |
|[pic] |
Console.log
• Used as a debugging tool
• Used with Chrome’s debugging features
|Chrome’s Console |
|[pic] |
Functions
• are small pieces of JavaScript code that can be run once or many times
• basis of JavaScript, and many other languages
• two types
o inline
▪ inside of another HTML tag
o called
▪ uses the tags to call a JavaScript function
• what a function looks like
| |// a function to display a message in an alert dialog |
| |function call_alert() |
|First Function |{ |
| |alert( "My First JavaScript Function" ); |
| |} |
| | |
| | |
| | |
| | |
| | |
| |[pic] |
• Things to notice
o function is a keyword to denote you are creating a function
o a function “name” is always followed by ( ), to denote a function
o to call the function, use the EXACT name, and ( )’s
o “onload” on tag in HTML will call the function before ANYTHING appears on the HTML document.
Create the HTML “functions.html” that will contain the HTML code above, and “functions.js” that will contain the JavaScript Code above. Get it to run.
| |// a function to display the value of a passed argument |
| |function call_alert( str ) // str is an “alias” |
|Function Arguments |{ |
| |alert( str ); |
| |} |
| | |
| | |
| | |
| | |
| | |
| |[pic] |
• Things to notice
o function call, has a string physically placed inside
o parameter in call_alert function is an alias
o values ARE CHANGED if reassigned
▪ not like some programming languages
▪ (may need to remind me later!!)
With debugging on in CHNrome, intentionally make a mikstake. What happens
Explanation of Mathematical Operations
|Symbol |Means |Example |
|! |Not |if(answer != ‘Q’) |
|++ / -- |incrementing/decrementing |covered later |
|% |modulus - remainder |covered later |
|+ - / * |normal arithmetic symbols | |
|< |less than |4 < 8 = = True |
| 4 = = True |
|>= |greater than or equal to |6 > = 6 = = True |
|= = |used to COMPARE – if they are equal |if ( answer = = ‘Q’) |
|! = |used to COMPARE – if they are NOT equal |if(answer != ‘Q’) |
|&& |And |covered later |
|| | |Or |covered later |
|Comparison Examples |
|[pic] |
|var teststrings1 = ( "JavaScript" == "JavaScript" ); |
|var teststrings2 = ( "JavaScript" == "javascript" ); |
|var testnumbers1 = ( 1.785 == 1.785 ); |
|var testnumbers2 = ( 5 != 5 ); |
|var testbooleans1 = ( true == true ); |
|var testbooleans2 = ( false != false ); |
|var testlessthan1 = ( 100 < 200 ); |
|var testlessthan2 = ( 100 < 100 ); |
|var testlessthan_or_equal = ( 100 1 ); |
|var a = 8, b = 8.0, testvariables1 = ( a == b ); |
|var c = null, d = null, testvariables2 = ( c == d ); |
| |
|var result = "TEST STRINGS 1: "+ teststrings1+ " 2: " + teststrings2+ "\n\n"; |
|result += "TEST NUMBERS 1: " +testnumbers1+ " 2: " + testnumbers2+ "\n\n"; |
|result += "TEST BOOLEANS 1: " +testbooleans1 + " 2: " +testbooleans2+ "\n\n"; |
|result += "TEST LESS THAN 1: " +testlessthan1+ " 2: " +testlessthan2+ "\n\n"; |
|result += "TEST LESS THAN OR EQUAL: " +testlessthan_or_equal+ "\n\n"; |
|result += "TEST GREATER THAN: " +testgreaterthan+ "\n\n"; |
|result += "TEST VARIABLES 1: " +testvariables1+ " 2: " +testvariables2+ "\n\n"; |
| |
|alert(result); |
Order of Operations
|Highest priority |! ++x --x |
| |* / % (Modulus) |
| |+ - |
| |< >= |
| |= = (Identical) ! = (Not Identical) |
| |&& (And) |
|Lowest priority || | (Or) x++ x-- |
• Make sure you use ( )’s to speficy order you wish to calculate
a = b * c – d % e / f; // not clear
a = (b * c) – ((d % e) / f); // much clearer
|var addnum = 20 + 30; |[pic] |
|var addstr = "I love " + "JavaScript"; | |
|var sub = 35.75 - 28.25; | |
|var mul = 8 * 50; | |
|var mod = 65 % 2; | |
|var inc = 5 ; inc = ++inc; | |
|var dec = 5 ; dec = --dec; | |
|var result = "Addnum is " + addnum + "\n"; | |
|result += "Addstr is " + addstr + "\n"; | |
|result += "Sub is " + sub + "\n"; | |
|result += "Mul is " + mul + "\n"; | |
|result += "Mod is " + mod + "\n"; | |
|result += "Inc is " + inc + "\n"; | |
|result += "Dec is " + dec + "\n"; | |
|alert ( result ); | |
Compound Assignment Operators
|JavaScript's Shorthand Assignment Operators |
|operator |shorthand |equivalent |
|+= |X += Y |X = X + Y |
|-= |X -= Y |X = X - Y |
|*= |X *= Y |X = X * Y |
|/= |X /= Y |X = X / Y |
|%= |X %= Y |X = X % Y |
Logical Operators
|Operator |Meaning |
|&& |and |
|| | |or |
|! |not |
|Logical Examples |
|var a = true , b = false; |[pic] |
|var test1 = ( a && a ); // test both operands for true | |
|var test2 = ( a && b ); | |
|var test3 = ( b && b ); | |
|var test4 = ( a || b ); // test either operand for true | |
|var test5 = ( a || b ); | |
|var test6 = ( b || b ); | |
|var test7 = !a ; var test8 = !b; // invert values | |
|var result = "AND \n"; | |
|result += "1: " +test1+ " 2: " +test2+ " 3: "+test3; | |
|result += "\n\nOR\n"; | |
|result += "4: "+test4+" 5: "+test5+" 6: "+test6; | |
|result += "\n\nNOT\n7: " +test7+ " 8: " + test8; | |
|alert( result ); | |
Logical Expressions
• need to code for certain conditions
• conditions can be exact, or wide ranging
• computer will actually match up conditions with code you create
• watch for conditions that are very much alike
• prepare for ANY possible condition, even if you think it’s impossible
• types in coding
o if/else’s
o if/else –if’s
o logical symbols used to compare
|If – prompt example |
|// initialize a variable with a null value |[pic] |
|var username = null; | |
| |[pic] |
|if ( username == null ) | |
|{ | |
|// ask the user for their name | |
|username = prompt( "Please Enter Your Name", "" ); | |
|// ... or greet the user by name | |
|if ( username != "" ) | |
|{alert( "Welcome " + username ); } | |
|} | |
|If – Else example |
|var num = 2, bool = false; |[pic] |
|// is the number 1 and the boolean value true ? | |
|if(num == 1 && bool == 1) | |
|{ alert("TEST1 bool: " + bool); } | |
|else if(num == 2 && bool == 1) | |
|// is the number 2 and the boolean value true ? | |
|{ alert("TEST2 bool: " + bool); } | |
|else if(num == 2 && bool == 0) | |
|// is the number 2 and the boolean value false ? | |
|{ alert("TEST3 bool: " + bool); } | |
|else if(num == 3 && bool == 0) | |
|// is the number 3 and the boolean value false ? | |
|{ alert("TEST4 bool: " + bool); } | |
Switch Statement
• may be more efficient to use a switch statement if we know a limited range of ONE variable
• PLEASE USE BLS!!!! (Block like Structure)
• works in a weird way
o evaluates the given expression
o then it seeks a clause that matches the value
o keywords used
▪ case
• denotes a clause
▪ default
• if no clauses match, uses THIS line as a default clause
• does NOT have a break after since LAST in list
▪ break
• all cases use, after LAST line in case statement
• breaks out of switch statement
|Switch Statement Example |
|var num = 2; |[pic] |
|switch(num) | |
|{ | |
|// is the number 1 ? | |
|case 1 : alert("This is case 1 code"); break; | |
|// is the number 2 ? | |
|case 2 : alert("This is case 2 code"); break; | |
|// is the number 3 ? | |
|case 3 : alert("This is case 3 code"); break; | |
|// if none of those numbers do this... | |
|default : alert("This is default code"); | |
|} | |
For Loop
- puts all there parts (testing, initialization, incrementing) in one line
for ( initialization; test; increment/decrement)
{
statements;
….
}
• The statements inside the {} are repeated until the condition of the test is met.
• ** Make sure { }’s are in Block Like structure!!!
• used when you know EXACTLY when the loop should, or how many times the loop should run before it ends
• NONE of the three stages HAVE TO BE set, in order to work
o could have a totally empty for loop
o for( ; ; ) // unusual though
|For Loop Example |
|var a = 0, b = 0; |[pic] |
|// initialize counter at zero then loop until it hits 5 | |
|for( var i = 0; i < 5; i++ ) | |
|{ | |
|// increment variable values on each iteration | |
|a += 10; b += 5; | |
|} | |
|// display the final values after the loop ends... | |
|alert( "FOR LOOP\n\n A is " + a + "... B is " + b ); | |
Create a for loop that will decrement a variable from 100 to 10.
CONTINUE AND BREAK CODING EXAMPLES
BREAK – “breaks” entirely out of the loop (inner most if nested loop)
CONTINUE – skips rest of code under reserved word, but “continues” loop
Using the With Statements
• not like any previous
• accesses on HTML that calls it
• must identify the form, and GUI component name
• “document” is the HTML document that called this function
• must place tag inside the , and AFTER the tag
• uses the syntax
document.forms.formname.nameofGUI.value = “something”;
|With statement Example |
| |// set values for user and city fields of the order form |
| |with( document.forms.order ) |
|With example |{ |
| |user.value = "Mike"; |
| |city.value = "New York"; |
| |} |
| | |
| | |
| | |
| | |
|Name: | |
| | |
| | |
|City: | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |[pic] |
One Dimensional Arrays
0 1 2 3 4 5 6 7 8 9 10 11 …
x …
array name element index
NOTICE:
max_index + 1 = size
index starts at 0 not 1!!
Holds ONLY ONE value per element!!
Homogeneous -- all of the elements have to be of the same type, e.g., int, float, char, etc.
declaration: (2 ways actually)
// create a blank array
var z = new Array( );
// create and initialize three new arrays
var a = new Array("Jan ", "Feb ", "Mar ");
var b = new Array("21, ", "22, ", "23, ");
var c = new Array(" 2003", " 2004", " 2005");
var scores = new Array(35, 17, 25);
Draw what the “a” array would look like:
Editing an element
arrayname[index] = value;
ex. sodaPrice[0] = .65; alphabet[0] = ‘A’;
Using the “Length” feature for an Array
• Using length is a great way of reducing code
• whenever used, it will give the SIZE of the array (or matrix)
• great STOPPER for “for loops”
a.length // “a” is the name of the array above
uses:
alert( “The size of this array is: “ x.length);
int size = x.length;
for(int i = 0; i < x.length; i++)
{ alert(x[i]); }
Join Function for arrays
• instead of the example above using for loops to display the entire array, use this
• parameter in join function will be placed in between EACH element in array
|Join example |
|// create a new array |[pic] |
|var a = new Array(); | |
| | |
|// put a word in seven array elements | |
|a[0] = "It"; | |
|a[1] = "isn\’t"; | |
|a[2] = "rocket"; | |
|a[3] = "science -"; | |
|a[4] = "it\’s"; | |
|a[5] = "just"; | |
|a[6] = "JavaScript"; | |
| | |
|// display all words in the array, separated // by a space | |
|alert( a.join(" ") ); | |
Reversing data in an Array
• does just that
|Reverse function example |
|// create a new array of image URLs |[pic] |
|var imgs = new Array("img1.gif","img2.gif","img3.gif"); | |
| | |
|// create a control variable | |
|var rev = false; | |
| | |
|// when the slideshow displays the final image | |
|// ...reverse the order | |
|rev = true; | |
|if( rev == true ) | |
|{ | |
|imgs.reverse(); | |
|} | |
| | |
|// display the reversed element order | |
|alert( imgs.join(" - ") ); | |
Sorting data in an Array
• sorts ALL types of data
• use same syntax above, with “.sort( )” at end
Working with Strings, finding the String’s length
• much like the length used in array
|String length Function Example |
|// create and initialize a string variable |[pic] |
|var a = "JavaScript Strings"; | |
| | |
|// display the length of the string | |
|alert("String length is " + a.length ); | |
CharAt(i) function for Strings
var word = “Apple”;
• returns letter at position “i” in String
char letter = word.charAt(2); // p
Concatenation or Joining Strings
var String1 = “Goodbye”;
var String2 = “, Cruel ”;
String1 = String1 + String2;
String1 = String1 + “World!”;
// String1 now contains “Goodbye, Cruel World!”
|G |
| |
| |
| |
|New Page 1 |
| |
| |
| |
|This line was originally written in the HTML |
| |
| |
|WriteLine.js |
|document.writeln("Mr. L needs a life"); |
|document.writeln("Mr. L REALLY NEEDS A LIFE!!!"); |
|document.writeln("OK, maybe just a girlfriend!!"); |
| |
|// NOTICE ANY " within the HTML code needs to be changed to ' |
|[pic] |
Linking JavaScript Data to the Form (The Date object)
• any data that is calculated in the JavaScript program
o can be send to the HTML
o IF IT HAS A FORM/GUI Component waiting for it
• Getting the Date
Detecting Errors
• Open the Console. Go to the screen where you are experiencing the error. In Chrome, navigate to View > Developer > JavaScript Console or More Tools > JavaScript Console or press Ctrl + Shift + J.
• Identify the Error. The error console will open. If you don't see any errors try reloading the page.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- using byid to change style
- professor kevin curran technology communicator
- byid university of delaware
- javascript writing into html output
- java script interview questions and answers
- index
- javascript is the scripting language of the web
- info cse 100 cheat sheet university of washington
- javascript texas a m university
Related searches
- texas a m money education center
- texas a m grading scale
- texas a m 2020 2021 academic schedule
- texas a m extension child care training
- texas a m academic calendar
- texas a m 1098 t
- texas a m campuses in texas
- texas a m financial aid portal
- texas a m university campuses
- texas a m online engineering degree
- texas a m online engineering masters
- texas a m college station tuition