0% found this document useful (0 votes)
8 views15 pages

Web Design Module VI

This document is a detailed study guide for Module VI, focusing on adding interactivity to websites using JavaScript. It covers scripting languages, JavaScript fundamentals, and techniques for manipulating web page elements, handling user events, and validating input. The guide includes practical steps for setting up a development environment and implementing JavaScript features to enhance user experience on web pages.

Uploaded by

betigistyemane64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Web Design Module VI

This document is a detailed study guide for Module VI, focusing on adding interactivity to websites using JavaScript. It covers scripting languages, JavaScript fundamentals, and techniques for manipulating web page elements, handling user events, and validating input. The guide includes practical steps for setting up a development environment and implementing JavaScript features to enhance user experience on web pages.

Uploaded by

betigistyemane64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Module VI: Apply Interactivity to a Website - Detailed Study Guide

Introduction:
This module introduces the concepts and techniques needed to add dynamic and interactive
elements to websites. You will learn about scripting languages, specifically JavaScript, and how
it's used alongside HTML and CSS to create engaging user experiences. We'll cover JavaScript
fundamentals, how to control program flow, use functions, manipulate web page elements (DOM),
handle user events, and validate user input in forms.

Unit 1: SCRIPTING LANGUAGE

1.1 Identify scripting language

• Concept: A scripting language is a type of programming language that is typically


interpreted at runtime rather than compiled beforehand. They are often used to automate
tasks, control software applications, or add dynamic behavior, especially in web
development.

• Key Characteristics:

o Interpreted Execution: Code is executed directly by an interpreter line-by-line or


just-in-time, without needing a separate compilation step into machine code.

o High-level Syntax: Often feature simpler, more readable syntax compared to


lower-level compiled languages, making them easier for beginners.

o Dynamic Typing: Variable types are usually determined at runtime, offering


flexibility (you don't always have to declare the type explicitly).

o Built-in Libraries/Frameworks: Often come with extensive libraries to simplify


common tasks and interact with systems or APIs.

o Flexibility and Rapid Development: Designed to allow for quick development


cycles and modifications.

• Examples: JavaScript (web client-side & server-side via Node.js), Python, Ruby, PHP,
Perl, Bash (shell script), PowerShell.
• Note: The line between scripting and general-purpose languages can sometimes be blurry.
These characteristics help identify a language's common usage as a scripting language.

1.2 Introduction to JavaScript (JS)

• Concept: JavaScript is the primary scripting language used to add interactivity to websites.
It allows developers to create dynamic content, handle user actions, validate forms, make
asynchronous requests, and much more, transforming static HTML pages into engaging
experiences.

• 1.2.1. Preface of JavaScript:

o Definition: JavaScript is a high-level, interpreted (or JIT-compiled) programming


language.

o Origin: Developed by Brendan Eich at Netscape in 1995 (initially Mocha, then


LiveScript).

o Purpose: Primarily created to add interactivity to web pages on the client-side (in
the browser). It enables manipulation of the DOM (Document Object Model) and
the creation of responsive user interfaces.

o Role: Complements HTML (structure) and CSS (style) by adding behavior.

• 1.2.2. Role of JavaScript in web development:

o Core Function: Enables dynamic and interactive features on web pages (client-
side).

o Capabilities: Enhances user experience, validates form inputs, creates interactive


elements (sliders, menus), handles events (clicks, keypresses), fetches data from
APIs, manipulates DOM.

o Beyond the Browser: Used for server-side development (Node.js) and mobile app
development (React Native, etc.).

o Ecosystem: Benefits from numerous frameworks (React, Angular, Vue) and


libraries (jQuery) that simplify development.
o Importance: Essential language for web development; indispensable for modern,
interactive web applications and SPAs (Single Page Applications).

o Advantages of Learning: MUST for web developers, most popular language, easy
setup (runs in all browsers), enables beautiful/fast/interactive websites, opens
opportunities in mobile/desktop/game development, high job demand/pay, rich
ecosystem of tools.

• 1.2.3. Features of JavaScript: (Referencing Fig 1.1.1 and surrounding text)

o Object-Centered Script Language: Has built-in objects (like the window object).
Supports object-oriented features like polymorphism.

o Client Edge Technology: Runs primarily in the user's web browser (the client),
allowing control over content rendering and interaction without constant server
communication.

o Validation of User's Input: Crucial for form validation, checking user-entered


data directly in the browser before submission.

o If and Else Statement: Supports conditional logic to execute different code paths
based on conditions.

o Interpreter Centered: Code is typically interpreted or JIT-compiled by the


browser's JavaScript engine, allowing direct execution without a separate
compilation step.

o Ability to Perform in Built-in Functions: Provides many built-in functions


(like isNaN(), parseInt(), parseFloat()) for common tasks.

o Case Sensitive Format: JavaScript distinguishes between uppercase and


lowercase letters (e.g., myVariable is different from myvariable).

o Light Weight and Delicate: Often described as lightweight; uses objects to


perform operations, variables don't always need explicit types.

o Statements Looping: Provides structures (loops) to execute blocks of code


repeatedly.
o Handling Events: Can respond to user actions (clicks, mouse movements, key
presses) and other browser events.

o Other Key Features: DOM Manipulation, Asynchronous Programming (AJAX,


Promises, async/await), Cross-Browser Compatibility, Extensibility
(libraries/frameworks), Dynamic Typing.

• 1.2.4. Application of JavaScript:

o Client-side validation: Verifying user input in forms before server submission.

o Manipulating HTML Pages: Dynamically adding, deleting, or modifying HTML


elements and content.

o User Notifications: Creating dynamic pop-ups or alerts.

o Back-end Data Loading (AJAX): Fetching data from the server without reloading
the page.

o Presentations: Creating web-based slide presentations (e.g., using RevealJS).

o Server Applications: Building server-side applications using Node.js.

o Advantages: Less server interaction (client-side validation), Immediate feedback


to users, Increased interactivity, Richer interfaces (drag-and-drop, sliders).

o Limitations: Client-side JS cannot directly read/write files on the user's computer


(for security), No built-in multi-threading/multiprocessor capabilities (though
concepts like Web Workers exist).

• 1.2.5. Setting up the JavaScript development environment:

o Requirements: A text editor or IDE, and a web browser.

o Steps:

1. Install Editor/IDE: Choose and install a code editor (e.g., VS Code,


Sublime Text, Atom, Notepad++) or IDE (e.g., WebStorm).
2. Install Browser: Use an existing browser or install one (e.g., Chrome,
Firefox, Edge, Safari, Opera).

3. Create Project Directory: Make a folder for your project files.

4. Create HTML File: Create the main .html file for your webpage.

5. Link/Embed JS: Include JavaScript using <script> tags (either inline or


linking an external .js file via the src attribute).

6. Start Coding & Testing: Write JS code, open the HTML file in the
browser, use browser developer tools (F12) for debugging.

o Tools:

▪ Browsers: Microsoft Edge, Google Chrome, Mozilla Firefox, Safari,


Opera.

▪ Editors/IDEs: Visual Studio Code (free), Eclipse (free), Atom (free),


Notepad++ (free, Windows), Code Lobster (free), WebStorm (paid).

▪ Online Editors: jsfiddle.net, jsbin.com, playcode.io (allow quick testing


without local setup).

• 1.2.6. Method to insert scripts in HTML document:

o Inline Script: Placing JavaScript code directly


between <script> and </script> tags within the HTML file (in <head> or <body>).
Placing scripts just before the closing </body> tag is often recommended for
performance.

▪ Example:

<body>

<h1>JavaScript Tutorials</h1>

<script>

alert('Hello, how are you?');


</script>

</body>

o External Script File: Writing JavaScript code in a separate .js file and linking it
using the src attribute of the <script> tag.

▪ Example: <script src="/MyJavaScriptFile.js"></script>

o Multiple Scripts: An HTML page can contain multiple <script> tags, executed in
the order they appear.

o type Attribute: Historically (HTML4), type="text/javascript" was required. In


HTML5, it's the default and usually omitted.

o Global Attributes for <script> tag:

▪ async: Executes script asynchronously with page parsing.

▪ crossorigin: Configures CORS requests for external scripts.

▪ defer: Executes script after the document is parsed but


before DOMContentLoaded.

▪ src: Specifies the URI/path of an external script file.

▪ type: Specifies the MIME type of the script (default is text/javascript).

▪ referrerpolicy: Specifies referrer information sent when fetching the script.

▪ integrity: Allows browser to verify fetched resource integrity (Subresource


Integrity).

▪ nomodule: Script should not execute in browsers supporting ES2015


modules.
Unit 2: Apply INTERACTIVITY USING JAVASCRIPT

2.1 Overview of interactivity using JavaScript

• Concept: This unit focuses on using JavaScript to transform static web pages into
dynamic, interactive experiences. It covers the core language features needed to respond
to user actions and manipulate page content. JavaScript is the key technology for client-
side programming, executing within the user's browser to update content, validate forms,
create animations, and more, without needing to reload the entire page.

2.2 JavaScript Syntax and Basic Concepts

• 2.2.1 Variables, Data Types, and Operators: (Covered in detail in Unit 1, Section 1.2 -
review these concepts: let, const, primitive types
like Number, String, Boolean, Null, Undefined, structural types like Object, Array, and
operators like arithmetic, comparison, logical, assignment, ternary).

• 2.1.1.2 Comments (Revisiting): Essential for explaining code. Single-line (//) and Multi-
line (/* ... */). Can be used to temporarily disable code for testing.

o Example:

// Single line comment

/* Multi-line

comment */

// document.getElementById('test').style.display = 'none'; // Temporarily hide element

• 2.1.2 Statements, Expressions, and Comments (Revisiting):

o Statements: Instructions for the computer (e.g., let a =


5;, document.getElementById("demo").innerHTML = "Hello";). Usually end with
a semicolon (;), which is recommended.

o Expressions: Code fragments that evaluate to a value (e.g., 5 * 10, x + y, "Hello"


+ " " + "World").
o Code Blocks: Grouping statements within curly braces {} (used in functions,
loops, conditionals).

o Whitespace: JavaScript largely ignores extra spaces and tabs, use them for
readability.

o Case Sensitivity: JavaScript differentiates between uppercase and lowercase


(e.g., myVar vs myvar).

• 2.1.3 Type Conversions:

o Explicit Conversion: Manually converting data types using built-in functions


like parseInt(), parseFloat(), String(), Number(), Boolean().

o Implicit Conversion: Automatic conversion by JavaScript during operations


(e.g., "5" + 1 results in "51"). Can lead to unexpected results (pitfalls).

2.3 Control Structures and Loops

• 2.3.1 Conditional Statements: Controlling code execution based on conditions.

o if: Executes code block if a condition is true.

▪ Example: if (x > 0) { alert("Positive"); }

o if...else: Executes one block if true, another if false.

▪ Example: if (age >= 18) { status = "Adult"; } else { status = "Minor"; }

o else if: Allows checking multiple conditions sequentially.

▪ Example: if (score > 90) { grade = 'A'; } else if (score > 80) { grade = 'B'; }
else { grade = 'C'; }

o Note: Curly braces {} optional for single-statement blocks but recommended for
clarity.

• 2.3.2 Looping Structures: Repeating code execution.

o for loop: Executes a block a specific number of times. Syntax: for (initializer;
condition; iteration) { ... }.
▪ Example (basic): for (let i = 0; i < 5; i++) { console.log(i); }

▪ Example (array): var arr = [10, 20, 30]; for (var i = 0; i < arr.length; i++) {
console.log(arr[i]); }

o Note: Initializer, condition, and iteration parts are optional within


the for() parentheses if handled elsewhere (e.g., initializer before loop,
condition/iteration inside loop block with break).

• 2.3.3 Break and Continue Statements:

o break: Exits the current loop prematurely.

o continue: Skips the rest of the current loop iteration and proceeds to the next one.

• 2.3.4 Error Handling: Managing runtime errors gracefully.

o try...catch...finally block:

▪ try: Contains code that might throw an error.

▪ catch(ex): Executes if an error occurs in the try block. ex often contains


error details.

▪ finally: Executes regardless of whether an error occurred or not (for


cleanup).

▪ Example:

try {

let result = riskyFunction();

console.log(result);

} catch (error) {

console.error("An error occurred: " + error.message);

} finally {

console.log("Execution finished.");
}

o throw statement: Used to create custom errors. Can throw strings, numbers,
booleans, or objects.

▪ Example: if (x < 0) { throw "Value cannot be negative"; }

▪ Example (object): throw { number: 101, message: "Invalid input" };

2.4 Functions in JavaScript

• Concept: Reusable blocks of code that perform specific tasks. Key for organization and
reducing repetition. Statements often start with a keyword like function.

• 2.4.1 Defining and Invoking Functions:

o Function Declaration: Uses the function keyword, followed by name, parameters,


and code block {}. Declarations are hoisted.

▪ Example: function greet(name) { alert("Hello " + name); }

o Calling (Invoking): Using the function name followed by parentheses (), passing
arguments if needed.

▪ Example: greet("Abebe");

• 2.4.2 Function Expressions and Anonymous Functions:

o Function Expression: Assigning a function definition to a variable. Not hoisted.

▪ Example: let calculateArea = function(width, height) { return width *


height; }; let area = calculateArea(5, 4);

o Anonymous Function: A function without a name. Often used in expressions or


as arguments (callbacks).

▪ Example (in expression): let multiply = function(a, b) { return a * b; };

▪ Example (callback): numbers.map(function(num) { return num * 2; });

• 2.4.3 Arrow Functions and Their Syntax:


o Concept: Introduced in ES6, provide a more concise syntax for writing functions,
especially anonymous ones. They do not have their own this value (lexical this).

o Syntax: (param1, param2) => expression or (param1, param2) => { statements }.

o Example (shorter): let square = x => x * x;

o Example (with block): let add = (a, b) => { let sum = a + b; return sum; };

o this Behavior: Arrow functions inherit this from the surrounding (lexical) scope,
unlike regular functions where this depends on how the function is called.

• 2.4.4 Parameters, Arguments, and Default Values:

o Parameters: Variables listed in the function definition.

o Arguments: Actual values passed to the function when called.

o Dynamic Typing: Parameters do not have fixed types.

o Mismatch: Fewer arguments passed result in undefined for missing parameters.


Extra arguments are ignored (but accessible via the arguments object in non-arrow
functions).

o Return Value: Functions use the return keyword to send a value back. If return is
omitted or used without a value, the function returns undefined. Functions can
return any data type, including other functions.

• (Implied) String Review (Covered in 2.2): Review string literals, template strings,
accessing characters, concatenation, String objects vs literals, comparison methods.

• (Implied) Scope Review (Covered in 2.2): Review global vs local scope.

2.5 DOM Manipulation and Event Handling

• Concept: JavaScript interacts with the HTML structure (DOM) to make pages dynamic.
Event handling allows JS to respond to user actions.

• DOM (Document Object Model): A tree-like representation of the HTML page. JS can
access nodes (elements, text, attributes) and modify them.
• Event Handling: Executing JS code in response to events like clicks (onclick), page loads
(onload), key presses, mouse movements, form submissions (onsubmit), input changes
(onchange, oninput).

• Importance: These two concepts combined allow for creating truly interactive web
applications.

2.6 Document Object Model (DOM)

• Arrays in JS (Context for DOM manipulation examples):

o Definition: Special variables holding multiple values. Created using


literal [] or new Array().

o Indexing: Zero-based index (arrayName[0]).

o length Property: Gets the number of elements.

o Accessing: Use index arrayName[index] or arrayName.at(index) (allows negative


index).

o Iterating: Use forEach, for, for...of, for...in.

o Adding Elements: By index (arrayName[index] =


value), push() (end), unshift() (start).

o Removing Elements: pop() (end), shift() (start). Middle elements require creating
new arrays (e.g., using filter).

• Event Handling and Propagation (Revisiting):

o HTML Event Attributes: onclick, onload, onunload, oninput, onchange, etc.


Assign JS code directly or call functions.

▪ Example: <h1 onclick="this.innerHTML = 'Changed!'">Click Me</h1>

▪ Example: <button onclick="myFunction()">Run Code</button>

o Assigning Events via DOM: Using JavaScript to attach functions to element event
properties (e.g., element.onclick = functionName;).
▪ Example: document.getElementById("myBtn").onclick = displayDate;

o Note: Modern approach uses addEventListener() (not covered in detail in this PDF
section).
Unit 3: VALIDATING USER INPUT

3.1 Validating User Input

• 3.1.1 Introduction to Validation:

o Definition: The process of checking if user-provided input meets specific rules or


constraints.

o Purpose: Ensure data is accurate, complete, appropriate, prevent errors, improve


data quality, enhance security.

o Applies to: Text fields, checkboxes, radio buttons, dropdowns, file uploads, etc.

• 3.1.2 Form Validation:

o Concept: Specifically validating data entered into web forms before submission.

o Methods:

▪ Client-Side: Validation performed in the user's browser using JavaScript or


HTML5 attributes. Provides immediate feedback.

▪ Server-Side: Validation performed on the server after data submission.


Essential for security and data integrity.

o JavaScript Validation (Example 1):

▪ Get form elements (e.g., document.getElementById).

▪ Attach function to onsubmit event.

▪ Use event.preventDefault() to stop submission if validation fails.

▪ Check conditions (e.g., input.value === "").

▪ Use alert() or modify DOM to show error messages.

▪ Return false to stop submission or allow default/use form.submit() if valid.

o HTML5 Validation Attributes + JS (Example 2 & 3):


▪ Use HTML5 attributes
like required, minlength, maxlength, type="email", type="number", patter
n, min, max, step.

▪ Use the form.checkValidity() method in JavaScript to check if all HTML5


constraints are met.

▪ Use event.preventDefault() if checkValidity() is false or if custom JS


validation fails (like password matching).

o Importance: Crucial for usability (immediate feedback), data integrity, and


security (preventing bad data). Server-side validation is always necessary as client-
side can be bypassed.

You might also like