JavaScript Part 2 Organizing JavaScript Code into Functions

Slides:



Advertisements
Similar presentations
Modifying existing content Adding/Removing content on a page using jQuery.
Advertisements

Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Introduction.  The scripting language most often used for client-side web development.  Influenced by many programming languages, easier for nonprogrammers.
Definition CSS “Short for Cascading Style Sheets, a new feature being added to HTML that gives both Web site developers and users more control over how.
 2000 Deitel & Associates, Inc. All rights reserved. Outline 8.1Introduction 8.2A Simple Program: Printing a Line of Text in a Web Page 8.3Another JavaScript.
JavaScript, Fourth Edition
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.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
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 Part 1 Introduction to scripting The ‘alert’ function.
JavaScript: Conditionals contd.
Intro to Dynamic HTML Forms - Part 1
Getting Started With HTML
JavaScript Controlling the flow of your programs with ‘if’ statements
Precedence Operators Error Types
HTML5 Basics.
Event-Driven Programming
Moving away from alert() Using innerHTML Using an empty div section
In this session, you will learn to:
Unit M Programming Web Pages with
User-Written Functions
Predefined Functions Using the JavaScript Documentation
Checkboxes, Select boxes, Radio buttons,
Essential Tags Web Design – Sec 3-3
Concatenation Comments
Loops BIS1523 – Lecture 10.
JavaScript Wrap-up.
Concepts of HTML, CSS and Javascript
Unit M Programming Web Pages with
Section 17.1 Section 17.2 Add an audio file using HTML
EGR 2261 Unit 4 Control Structures I: Selection
Retrieving information from forms
JavaScript Part 2 Organizing JavaScript Code into Functions
Introduction to JavaScript
Introduction to JavaScript
Understanding JavaScript and Coding Essentials
A second look at JavaScript
Introduction to JavaScript
JavaScript – Part I Mendelsohn.
JavaScript Variables.
Document Structure & HTML
Introduction to JavaScript
Introduction to Programming and JavaScript
Javascript Chapter 19 and 20 5/3/2019.
Selection Statements Chapter 3.
JavaScript and Ajax (JavaScript Events)
Introduction to JavaScript
Web Programming and Design
Events Part I Mouse Events.
Selectors.
Modifying HTML attributes and CSS values
JavaScript Variables.
A Few Notes on JavaScript
HTML Forms, Part 1 Image taken from "How to structure an HTML form" from Mozilla Developer Network.
Getting Started With Web Page Creation Using HTML
Internal Style Sheets External Style Sheets
Retrieving information from forms
Checkboxes, Select boxes, Radio buttons
The W3C More on images Entity codes Remote vs Local Computers
CSS Classes.
Introduction to scripting
JavaScript Variables.
Adios alert() Using innerHTML Using an empty section
Concatenation of Strings JavaScript Comments
<div> <span>
Presentation transcript:

JavaScript Part 2 Organizing JavaScript Code into Functions Invoking JavaScript Functions

Learning Objectives By the end of this lecture, you should be able to: Describe the difference between stand-alone code as opposed to code contained inside a function Explain what is meant by the term ‘invoke’ Create a JavaScript function Connect your HTML code to a function via the onclick attribute Explain why it is important to refresh your page constantly FROM MEMORY: Be able to create a very simple JS function, and invoke that function from a form

Organizing scripts into functions While it is possible to place individual lines of script anywhere inside an HTML document, we will now begin using the following technique: We will organize our JavaScript code by dividing specific tasks into "functions". We will place these functions immediately before the </body> tag of our html documents.

Writing a JS Function All functions begin with the word: function function greetTheUser() { alert("Hello, user!"); alert("I hope you have a nice day."); } All functions begin with the word: function All functions must have a name (“identifier”) Naming conventions (yup, another one) to use when naming a JS function: First letter uncapitalized and all subsequent words should be capitalized (known as “camel case”) No spaces between words Avoid “reserved” words (function, if, return, etc, etc) This is the same naming convention we are using when naming form elements The function name is followed by parentheses: () Later we will discuss what information can go inside these parentheses The beginning and end of the body of the function must be delineated by braces: { and } Note that while nearly all lines of JS code end with a semicolon, this does NOT apply to function declarations (i.e. the first line of the function).

Reminder: Clarity function myFirstFunction( ) { alert("My first try at a function."); alert("I hope it works."); } Note how each brace is placed on its own line Many programmers like to place the first brace on the same line as the function declaration (the first line). This is perfectly acceptable. You will see both used in this course. Note how every statement inside the function is indented Note the ‘camel case’ convention for naming the function Note that there is NO semicolon at the end of the function declaration

Code inside a function v.s. Stand-Alone code The JS code below has not been placed inside a function. Therefore, this code will be automatically executed every single time the page runs. Also, when you execute this page, you may be surprised to see that even though the JS code is placed at the very end of the document, it is executed before any of the HTML code is displayed! <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Functions Example</title> </head> <body> <h2>Some JS code...</h2> Note how the JS code is executed automatically when the page loads. <script> alert("Hello..."); </script> </body> </html>

Stand-Alone code v.s. Code inside a function If we place our JS code inside of a function, the code is NOT executed automatically. This allows us to control if and when the code is executed. This is almost always the desirable way of doing things. By placing JS code inside a function, It means that the code only gets executed when we want it to. Recall that any stand-alone JS code is not only executed automatically, it is also executed before any of the HTML content on the page is displayed. It also means that we can execute the function multiple times if need be. It also means that we have the option of deciding that in a given situation the function should never be executed.

Code inside a function The JavaScript code on this particular page will never be executed. The code is contained inside a function – but at no point on the page did we ever invoke the function. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Functions Example</title> </head> <body> <h2>Some JS code...</h2> This JS code will never be executed! <script> function greetUser() { alert("Hello, user!"); } </script> </body> </html>

How to execute ("invoke") a JavaScript function There are two ways of invoking functions that we will focus on during this course: Via a JavaScript command (discussed later) Via an HTML attribute called onclick

How to invoke a function: --The onclick attribute -- The onclick attribute is most commonly applied to an HTML button. It can be applied to other HTML tags as well, such as images, form elements, heading tags, etc. etc. The value given to the onclick attribute must match the name of your function. This includes the parentheses To connect the function to a button we must include the onclick attribute inside the button's tag: <input type="button" value="Greet the user" onclick="greetUser();" > <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Functions Example</title> </head> <body> <input type="button" value="Greet the user" onclick="greetUser();"> <script> function greetUser() { alert("Hello, user!"); } </script> </body> </html>

Bugs (Coding Errors)… Debugging is MUCH easier when it is caught early. If there is a lot of code on your page, finding a bug that was created earlier in the process can be VERY difficult. Just one small error can sometimes cause the entire page to fail to display! Key Point: Refresh your page CONSTANTLY. Don't type out multiple lines of code and then refresh. If you're not certain that you code is working, make sure you refresh your page to test it before moving on! This is arguably the single most important coding tip of the entire course!

Executing a script from a form In this course, we will nearly always execute our scripts in response to the user submitting an HTML form. Specifically, we will apply the onclick attribute to an HTML button. Let’s go through the process of creating a button that will execute a JavaScript function. The steps are: 1. Create the button 2. Write the JavaScript function 3. Connect the button to the function

The Greeting: I: The Button <form id="practiceForm"> <input type="button" value="Greet Me!" > </form> The Greeting: I: The Button

The Greeting: II: The Script <script> function greetUser() { alert("Hello, dear user!"); alert("Have a great day!"); } </script> The Greeting: II: The Script Pop-Quiz: Where in your HTML document should this script be placed? Answer: Just before </body>

The Greeting: III: Connect the button to the function. <form id="practiceForm"> <input type="button" value="Greet Me!" onclick="greetUser();"> </form> The value of the onclick attribute must precisely match the name of the JS function you wish to invoke (including the parentheses). The semicolon inside the attribute value is optional.

Complete Example <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Functions Example</title> </head> <body> <form id="practiceForm"> <input type="button" value="Greet Me!" onclick="greetUser();" > </form> <script> function greetUser( ) { alert("Hello..."); } </script> </body> </html> Aside: Note that the opening brace of the function is on the same line as the function declaration. This is fine – in fact, many users prefer to place it there. The closing brace, however, should always be on its own line.

A common error: The function declaration should NEVER have a semicolon after it. Doing so will cause the body of your function to never execute! function greetUser( ); { alert("Hello..."); } Never place a semicolon after your function declaration.

Example Web Page functions_example.html In addition to giving another example of the concepts discussed in this lecture, this page also demonstrates how you can have multiple functions on a single page. Having multiple functions on a page is common – and, in fact, is a very good way to organize your code.

Stop! Whatever you do, do NOT casually watch this lecture, knock off the quiz and mentally check the topic off your list! This, and subsequent JavaScript topics will involve many seemingly minor issues that can easily trip us up. There are quite a few small details that may appear insignificant right now, but will turn out to be very important. In other words, this is a KEY point in the course where you must make frequent stops in order to practice coding the concepts as they are being discussed. It is certainly a good idea to first watch the lecture all the way through. However, then be sure to go back and re-watch it again, making sure to practice every example along the way. Only move on to the next lecture AFTER you can carry out all of these steps on your own with few (preferably zero!) peeks at the notes.