Download presentation
Presentation is loading. Please wait.
1
CIS 388 Internet Programming
Javascript Part 2
2
Review – Part 1 Javascript is a client-side scripting (programming) janguage Java and Javascript are NOT the same thing Javascript has the same support for variables, programming methods/instructions and operators that most full-languages have. Javascript is NOT a markup language Javascript is a scripting language Does not need to be compiled Runs in a browser Javascript can be included in an HTML page with the <script> tag or in an external “.js” file.
3
Hello World! Javascript “Hello World” Alert Box <!DOCTYPE html>
<body> <script> alert('Hello, World!') </script> </body> </html>
4
Sample Javascript <html> <head> <title>Javascript Page</title> <style> body {background-color: #000;} .pagebody {margin: auto; margin-top: 15px; width: 75%; background-color: #fff; padding: 20px; text-align: center; border: double #000 5px;} </style> </script> function ChangeColor(color) { document.body.style.backgroundColor = color; } </head> <body> <div class="pagebody"> <h1>Hello World!</h1> <button type="button" onclick="ChangeColor('#00ff00')">Green</button> <button type="button" onclick="ChangeColor('#ff0000')">Red</button> <button type="button" onclick="ChangeColor('#0000ff')">Blue</button> </body> </html>
5
Programming Basics Syntax – Rules and structure of the programming language Reserved Words – Special words in the language that are used for instructions/programming and cannot be used as variable names, etc… Variables – unknown/changable values in a program to be stored/evaluated. Operators – special characters (mostly mathematical) used to evaluate variables (=,!=,+,-,/,*,<,>,and,or) Functions – reusable portions of code that can be subdivided and accept incoming values/variables and performs operations/instructions. Conditionals, Iterations/loops – common programming structures used to evaluate variable and perform certain instructions based on the evaluation (conditional) or repeat a series of instructions until a specific condition is met (loop)
6
Javascript Syntax Javascript is contained in an external “.js” file or between the “<script></script>” tags in a page. Javascript lines of code are ended with a semi-colon; Javascript comments are designated by double slashes “//” – *until the next line Functions (and conditionals, loops, etc…) are contained within brackets “{}” Operations with variables (+-*/) and evaluation of expressions are in parenthesis (*also indicates precedence) Nearly everything in JavaScript is an object — arrays, functions, numbers, even strings — and they all have properties and methods
7
Javascript Reserve Words
abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends final finally float for function goto if implements import in instanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try typeof var void volatile while with JavaScript has a number of “reserved words,” or words that have special meaning in the language. You should avoid using these words in your code except when using them with their intended meaning.
8
Javascript Variables JavaScript variables are containers for storing data values. JavaScript has dynamic types (loosely typed). This means that the same variable can be used to hold different data types. Variables do not have to be declared Variables are assigned as the top/beginning of the code/function Variables in functions (local) are available to nested functions(scope) variables that are declared inside a function without the var keyword are not local to the function — JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn’t previously defined, it will be defined in the global scope, which can have extremely unexpected consequences; Variable types are the standard types – strings, boolean, numeric, arrays, etc… Example: var foo = 'hello world';
9
Javascript Arrays A group of related variables referenced by index
Arrays are zero-indexed lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays. Example: var myArray = [ 'hello', 'world' ]; Example: myArray.length ( Length/values in the array -2) Example: myArray[1] = 'changed'; (change a value in the array) Example: myArray.push('new'); (add a value to the array) Other operations with arrays: var myArray = [ 'h', 'e', 'l', 'l', 'o' ]; var myString = myArray.join(''); // 'hello' var mySplit = myString.split(''); // [ 'h', 'e', 'l', 'l', 'o' ]
10
Default Values for Boolean Expressions
Values that evaluate to true '0'; 'any string'; []; // an empty array {}; // an empty object 1; // any non-zero number Values that evaluate to false 0; ''; // an empty string NaN; // JavaScript's "not-a-number" variable null; undefined; // be careful -- undefined can be redefined!
11
this Keyword In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked. The value of this is determined using a simple series of steps: If the function is invoked using Function.call or Function.apply, this will be set to the first argument passed to call/apply. If the first argument passed to call/apply is null or undefined, this will refer to the global object (which is the window object in Web browsers). If the function being invoked was created using Function.bind, this will be the first argument that was passed to bind at the time the function was created. If the function is being invoked as a method of an object, this will refer to that object. Otherwise, the function is being invoked as a standalone function not attached to any object, and this will refer to the global object.
12
Javascript Functions In JavaScript, functions are “first-class citizens” — they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery. Self-Executing-anonymous functions - creates a function expression and then immediately executes the function, no variables declared inside of the function are visible outside of it. Example: function foo() { /* do something */ }
13
Javascript Conditionals
Conditionals are generally used to evaluate whether a condition(s) is are true/false and perform actions, they can be nested to provide sub-conditions and actions can be performed if none of the conditions are met If-then-else - provides a conditional that can be easily nested (sub-conditions) and evaluated on in a limited set of curcumstances (this-or-that) Example: if (condition) { instructions; } While curly braces aren’t strictly required around single-line if statements, using them consistently, even when they aren’t strictly required, makes for vastly more readable code.
14
Javascript Conditionals
Switch/Case Statement – provides a conditional that can be easily evaluated based on a wide range of curcumstances (50 steps, which step is current?) Example: switch (variable) { case ‘1': instructions; break; case ‘2': instructions; break; default: instructions; break; }
15
Javascript Iterations/Loops
Loops let you run a block of code a certain number of times, until a condition is met. for loop is made up of four statements The initialisation statement is executed only once, before the loop starts. It gives you an opportunity to prepare or declare any variables. The conditional statement is executed before each iteration, and its return value decides whether or not the loop is to continue. If the conditional statement evaluates to a falsey value then the loop stops. The iteration statement is executed at the end of each iteration and gives you an opportunity to change the state of important variables. Typically, this will involve incrementing or decrementing a counter and thus bringing the loop ever closer to its end. The loopBody statement is what runs on every iteration. It can contain anything you want. You’ll typically have multiple statements that need to be executed and so will wrap them in a block ( {...}). Example: for (var i = 0, limit = 100; i < limit; i++) { instructions; }
16
Javascript Iterations/Loops
While Loop – code/instructions will keep executing until the condition evaluates to false. Example: while (i < 100) { instructions; i++; // increment i } D0-while Loop – This is almost exactly the same as the while loop, except for the fact that the loop’s body is executed at least once before the condition is tested. Example: do { alert('Hi there!'); } while (condition);
17
Javascript Examples Generate Alert Box if user tries to change text in text input field <FORM> <INPUT TYPE="text" VALUE= "dont change" NAME = "leavebutton" onChange= "alert('Please dont change this')"> </FORM> Show the date and time when the page loads <SCRIPT LANGUAGE = "Javascript"> var today= new Date() </SCRIPT> <BODY onload=alert(today)>
18
Javascript Examples Animate the background color of a document
<SCRIPT LANGUAGE= "javascript"> setTimeout("document.bgColor='white'", 1000) setTimeout("document.bgColor='lightpink'", 1500) setTimeout("document.bgColor = 'pink'", 2000) setTimeout("document.bgColor = 'deeppink'", 2500) setTimeout("document.bgColor = 'red'", 3000) setTimeout("document.bgColor = 'tomato'", 3500) setTimeout("document.bgColor = 'darkred'", 4000) </SCRIPT> Notice that the script is not just a series of document.bgColor = commands. You could write that script but the colors would change so quickly that you would not see the animated effect. We need to introduce a delay between each background color change. Javascript offers a setTimeout() method that allows creation of delays as well as serving other functions. The setTimeout() method requires two elements to be enclosed in its parentheses. The first element is an expression to be evaluated or acted upon. The second element is the number of milliseconds (thousandths of a second) to be waited before the first action is undertaken. setTimeout(expression to be evaluated, milliseconds)
19
Javascript Examples Scrolling Text: Jquery - is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. Jquery Tutorials: Jquery Samples: Jquery Resources:
20
Additional Resources W3 Schools Javascript tutorial: Javascript tutorials: Javascript scripts and code resources:
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.