A Few Notes on JavaScript

Slides:



Advertisements
Similar presentations
Introduction to JavaScript
Advertisements

Modifying existing content Adding/Removing content on a page using jQuery.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven.
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
Introduction to JavaScript. Aim To enable you to write you first JavaScript.
Random Stuff Colors Sizes CSS Shortcuts. Learning Objectives By the end of this lecture, you should be able to: – Identify the 3 most common ways in which.
Javascript and the Web Whys and Hows of Javascript.
JQuery and Forms – Part I. Learning Objectives By the end of this lecture, you should be able to: – Retrieve the values entered by a user into a form.
CS346 - Javascript 1, 21 Module 1 Introduction to JavaScript CS346.
Selectors. Learning Objectives By the end of this lecture, you should be able to: – Select items using jQuery based on ID, class name, or HTML tag. –
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
CSC 330 E-Commerce Teacher Ahmed Mumtaz Mustehsan Ahmed Mumtaz Mustehsan GM-IT CIIT Islamabad GM-IT CIIT Islamabad CIIT Virtual Campus, CIIT COMSATS Institute.
Introduction.  The scripting language most often used for client-side web development.  Influenced by many programming languages, easier for nonprogrammers.
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
Sahar Mosleh California State University San MarcosPage 1 JavaScript Basic.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
Changing HTML Attributes each() function Anonymous Functions $(this) keyword.
Review of HTML and CSS A (very) brief review of some key fundamentals to be aware of in IT-238.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
Tarik Booker CS 120 California State University, Los Angeles.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Cascading Style Sheets for layout
JavaScript Controlling the flow of your programs with ‘if’ statements
Precedence Operators Error Types
Module 1 Introduction to JavaScript
Build in Objects In JavaScript, almost "everything" is an object.
Event-Driven Programming
Moving away from alert() Using innerHTML Using an empty div section
HTML Elements with JavaScript and DOM Events
Checkboxes, Select boxes, Radio buttons,
Introduction to Python
Concatenation Comments
JavaScript Wrap-up.
Intro to JavaScript CS 1150 Spring 2017.
Cascading Style Sheets for layout
Retrieving information from forms
HTML.
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
JavaScript Part 2 Organizing JavaScript Code into Functions
Intro to PHP & Variables
Introduction to JavaScript
JavaScript Introduction
Introduction to JavaScript
JavaScript – Part I Mendelsohn.
Removing events Stopping an event’s normal behavior
Document Structure & HTML
Tutorial 10: Programming with javascript
Chapter 7 Event-Driven Pages
Introduction to JavaScript
Web Programming and Design
Introduction to Web programming
Adding/Removing content on a page using jQuery
Selectors.
Working with Strings.
Events Part III The event object.
Modifying HTML attributes and CSS values
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
HTML Forms, Part 1 Image taken from "How to structure an HTML form" from Mozilla Developer Network.
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Checkboxes, Select boxes, Radio buttons
Introduction to scripting
Adios alert() Using innerHTML Using an empty section
Concatenation of Strings JavaScript Comments
<div> <span>
Presentation transcript:

A Few Notes on JavaScript

Learning Objectives By the end of this lecture, you should be able to: Comment your code in JS Describe how commenting code can be used as a debugging technique Be able to use the document.write() to output HTML code using JavaScript Organize JS code into functions and demonstrate how to invoke a JS function both ‘explicitly’ and via the ‘onclick’ attribute of a button. Retrieve values from a form using the JS function getElementById()

Commenting Code in JavaScript In HTML and JS, a comment is text written in your source code that is ignored by the web browser. It is a great way for you to make notes to yourself and to other members of your programming team (either now or in the future). Do NOT underestimate the importance of comments! While you are in the process of writing your code, the purpose of a given statement may be very clear and obvious to you. However, to other programmers – and even to yourself in the future, this “obvious” code can quickly be a source of frustration and confusion. Why did I create that variable? This function seems superfluous – why is it there? Why did I program this section in this particular way? Comments in JavaScript are written differently than comments in HTML.

How to Comment in JS Two ways Placing two forward slashes // results in everything after the slashes being commented. You can place a ‘//’ comment on the same line as ‘live’ code: var ageVis1; //’ageVis1’ holds the age of the first visitor //this entire line is a comment If you wish to comment multiple lines, place /* at the beginning, and */ at the end: /* This program is written by Joe Schmoe DePaul University All Rights Reserved All of these lines are comments and will be ignored by the web browser when it parses your page. */

Comments are a GREAT debugging technique! If you have a block of JS code that you suspect contains a problem somewhere, you can temporarily remove one or more of the lines by simply “commenting them out”. Example: Suppose that in the following code, you are fairly confident that the alert statements are just fine, and that the reason your page is not displaying is a problem somewhere in the two middle lines.To check this, you can simply comment those two lines out. alert('hello world'); //var x = Math.Sqrt(33.4); //alert(x+5); alert('goodbye'); You can then remove each comment one at a time in order to determine at exactly which point the page stops working properly. In this case, when you remove the comment on line 2 making that line ‘active’, you will see that the page suddenly stops working. This gets you looking at that line with extra care, and hopefully you will spot the bug. (In this case, the capital ‘S’).

Single or Double Quotes? When working with Strings in JS, you can use either single quotes (‘) or double quotes (“). FYI: This flexibility is NOT as widely accepted with HTML. Generally, best to stick with double quotes for things like HTML attributes. However, there are a few exceptions which we may discuss down the road. alert("hello world"); //double quotes alert('hello world'); //single quotes – works just as well… I tend to use single quotes for Strings, but either is fine. There are some nuances that will show up down the road, in which case, we will return to the topic. My main suggestion for the time being is to use single quotes for strings and double quotes for attribute values. As was just mentioned, when surrounding the value of an attribute in HTML, I tend to prefer double quotes: <input type="text" id="txtFirstName">

document.write() Any content inside the parentheses of the write()function will be inserted as HTML into your HTML document. This also includes any CSS code: //output Hello World to a web page (not alert box) document.write('Hello world'); var firstName = 'Bob'; alert('Hello, ' + name + '.'); //outputs: Hello, Bob. Here is an example that includes HTML code: document.write('<h2>Hello world</h2>'); document.write('<hr>'); document.write('<p style="color:#ff0000;" >A paragraph of content...</p>'); There are some issues that can cause document.write() to act strangely. For this reason, we will only use this function sparingly. In a couple of weeks, we will have a discussion on some of the problems that can occur when using function and how to get around them. All you need to know for now is to be try and use only single-quotes to surround your strings, and double quotes to surround attributes.

Stand Alone JavaScript Code By ‘stand-alone’ code, I mean JS code that is not placed inside a function. JS code can be placed directly inside the <script> tag without using a function: <script> document.write('Today is ' + Date() + '<br>'); document.write('Hope that the weather is nice!'); </script> This ‘stand-alone’ code (as opposed to code inside a function) is fine if you intend that a given snippet of code should only be executed once. Also, stand-alone code will be executed every time the page loads. Stand-alone code will be executed exactly at the location where it appears in the source code of your web page. So if your JS code were embedded like so: <h2>Greetings!!</h2> <h3 style="color:red;"> document.write(Hope that the weather is nice!'); </h3> <!-- Note that the JS code is located inside the ‘h3’ tag --> Goodbye! Then the output would be:

JS Code inside a function However, we typically organize our code into functions. This allows us to run a given series of statements as often as we like by simply invoking (also known as “calling”) the function: <script> function printGreeting() { var message; message = 'Hello!' message = message + 'How are you today?'; message = message + 'The date is: ' + Date(); alert(message); } </script> Now whenever you wish to output this greeting information, you can simply type the JS code: printGreeting(); Be sure you are clear: If code is contained inside a function, that code will NOT be executed unless the function is explicitly invoked somewhere. Compare with stand-alone code that is not inside a function as was shown a moment ago. This code will always be executed when the page loads. That is, code that is not placed inside a function does not have to be invoked in order to be executed.

The HTML ‘onclick’ attribute For many of you, the only value you’ve given to the onclick attribute of a button is the name of a function: <input type="button" value="DO STUFF" onclick= "doStuff()" > However, you CAN give other JS commands directly inside – but you should limit them to a SINGLE JS statement. Also, you should NOT put in a semicolon. <input type="button" value="Greet Me!" onclick= "alert('Hello!')" > <input type="button" value= "Write the Date" onclick= "document.write( Date() )" > Note that there is no semicolon after the JS command inside the ‘onclick’ attribute. Though unusual, it is simply the way things are often done. If you have a JS command as the value of an HTML attribute, you do NOT include the semicolon. Also note how the HTML code for the ‘input’ tag in the last example is spread out over more than one line. Remember that clarity is extremely important when coding. If you think that it helps to spread a complicated bit of code over more than one line, then by all means do so! However, you should also be aware that many programmers find that using too much space makes code less clear! So definitely use whitespace, but use it judiciously.

REVIEW TIME In this course you will spend a great deal of time studying and analyzing code examples that I give you. Learning to program by studying examples of code that others have written is one of the best ways to advance your skills. In the files listed below, I have given detailed comments to help you do so. So be SURE to read the comments carefully as they include some important information. Files to review: js_review_one.htm invoke_js_function_button.htm

getElementById() Another important function that some of you may have not yet encountered. This getElementById() function essentially replaces the document.formName.elementName.value text that some of you may have used in the past. Why should we use this new function? As we have recently discussed, we are moving away from using ‘name’ and instead are now using ‘id’ when we name our form elements. Later on, we will discuss situations where we may still want to use the ‘name’ attribute as well as ‘id’. Suppose you have a web page with the following form elements: <input type="text" id="txtPhoneNumber"> <select id="selNationality"> <!– Note the use of the attribute ‘id’ instead of ‘name’ --> You can retrieve the value of those elements with the getElementById() function: var userPhoneNumber = document.getElementById('txtPhoneNumber').value; var nationality = document.getElementById('selNationality').value;

As discussed, the name of the game this week is review. Ya Gotta Code! As discussed, the name of the game this week is review. The key to learning code is to try out examples on your own and then experiment with them. Be sure to create some web pages in which you practice applying the following concepts/techniques. Some are very easy (e.g. comments), while others may need review such as using the parseInt/parseFloat functions, getElementById().value, getElementById().innerHTML All of these can be seen on the JavaScript review videos which you can find on my 'Resources' page. Using comments to document your code Using JS comments to debug code Using document.getElementById().value to retrieve values from a form Using document.getElementById().innerHTML --> see the museum_admission_238.htm example Using the parseInt and parseFloat functions when applicable Invoking JS functions (both explicitly, and via the HTML onclick attribute) Placing all of your HTML code inside sections using <div> or semantic tags I can not emphasize this enough. Do NOT fall into the trap of saying ‘Yeah, yeah, I got this.’ You will quickly see that there are many small things that you think you get that are in fact troublesome and quirky when you start doing it yourself. You will also find that typing out code brings to light certain misunderstandings or concepts that you had missed on the first go. When this happens (and it will!) don’t get discouraged! It is a good thing and is a very real part of the learning process when it comes to programming.