Primers-Web Development HTML
Primers-Web Development HTML
HTML Basics
1. HTML: Hyper Text Markup Language for creating web pages, websites,
and applications.
○ Hypertext: Text with embedded links.
○ Tags: Structural components (e.g., <html>, <body>).
○ Basic Tags:
■ <html>, <head>, <body>: Define the document structure.
■ <h1> to <h6>: Headings (h1 is largest, h6 is smallest).
■ <p>: Paragraphs.
■ <br>: Line breaks.
■ <hr>: Horizontal rules.
2. Comments: <-- Comment --> for code annotations (not displayed in
browsers).
3. Doctype: Specifies HTML version; must be the first line.
Static vs. Dynamic Web Pages
1. Static:
○ Unchanging, prebuilt content.
○ Written in HTML; no interaction or real-time updates.
○ Flexible designs.
2. Dynamic:
○ Content changes based on user or system input.
○ Uses client-side (JavaScript) or server-side scripting (e.g., PHP,
JSP).
○ Retrieves and updates data from databases.
HTML5 Features
1. New Elements:
○ <video> and <audio> for media.
○ <canvas> for graphics and drawing.
○ Semantic tags: <header>, <footer>, <nav>, <article>,
<aside>, etc.
2. Improved Input Controls:
○ New form types: email, date, time, url.
3. Offline Storage: Better local storage capabilities.
Tables
1. Tags:
○ <table>: Defines the table.
○ <tr>: Table row.
○ <th>: Table header cell.
○ <td>: Table data cell.
○ <caption>, <thead>, <tbody>, <tfoot>: Group table
content.
2. Attributes:
○ colspan: Merges columns.
○ rowspan: Merges rows.
Lists
1. Types:
○ Ordered List (<ol>): Numbered (1, A, a, I, i).
○ Unordered List (<ul>): Bulleted (disk, circle, square).
○ Description List (<dl>): Term-definition pairs.
2. List Items: Use <li> for items.
Links
Images
1. <img> Tag:
○ src: Image source URL.
○ alt: Alternate text.
○ height and width: Dimensions.
● Browsers render HTML even with missing end tags but may cause
errors.
● HTML5 is widely supported by modern browsers.
html
Copy code
<!DOCTYPE html> <!-- Line 1: Specifies the HTML version
(HTML5 here) -->
<html> <!-- Opening HTML tag -->
<head> <!-- Head section -->
<title>Page Title</title> <!-- Defines the
browser tab name -->
</head>
<body> <!-- Body section -->
<!-- Main content goes here -->
</body>
</html>
3. Tags Overview
● Opening and Closing Tags: Most tags come in pairs: <tag> (opening)
and </tag> (closing). Example: <p>Hello</p>.
● Self-Closing Tags: Some tags don't need a closing tag, e.g., <br> (line
break) or <hr> (horizontal rule).
● Block Elements:
○ Take up the full width of the page (stretch left to right).
○ Examples: <p>, <h1>, <div>.
● Inline Elements:
○ Occupy only the necessary width of their content.
○ Examples: <b> (bold text), <i> (italicized text).
Here:
HTML forms are used to collect user input, enabling interactivity between
users and applications.
Basic Structure
html
Copy code
<form action="url" method="post">
<!-- Form elements go here -->
</form>
1. Input Fields:
○ <input type="text">: Text input.
○ <input type="password">: Hidden text for passwords.
○ <input type="checkbox">: Toggle checkboxes.
○ <input type="radio">: Radio buttons (select one).
○ <input type="file">: Upload files.
○ <input type="submit">: Submit the form.
○ <input type="button">: Button for custom actions.
2. Other Elements:
○ <textarea>: Multiline text input.
○ <select>: Dropdown menus with <option>.
○ <fieldset>: Grouping form elements.
○ <label>: Label for form elements.
HTML5 introduced new features for better data handling and validation.
Form Attributes
Multimedia Elements
1. Audio:
○
○ Common formats: MP3, Ogg, WAV.
2. Video:
○
○ Common formats: MP4, WebM, Ogg.
3. Iframe:
Key Takeaways
A table is created using the <table> element. Rows are defined with <tr>,
and cells can be either:
1. <table>:
○ Defines the table.
○ Optionally, you can add a border attribute for visibility during
testing.
2. <thead>:
○ Contains the header row(s) using <tr> and <th> tags.
3. <tbody>:
○ Contains the main data rows using <tr> and <td> tags.
4. <tfoot>:
○ Contains the footer, often used for summaries or additional notes.
5. Structure Order:
○ <thead> comes first, followed by <tbody>, and finally <tfoot>.
Best Practices
Objective:
The goal is to create a dynamic table where customer details, such as names,
are added as they are typed into an input box. Additionally, you should be able
to delete selected customer details using checkboxes.
Key Concepts:
1. jQuery Selectors:
jQuery selectors are used to find and select HTML elements based on
various attributes like ID, class, type, or attribute values.
2. Capturing Input:
○ To capture the value typed in an input box, use the ID selector.
For example, using $("#name").val() will select the input field
with the ID name and capture its value.
○ This value is stored in a local variable for further manipulation.
3. Selecting a Button:
○ To capture the action of a button click (such as adding a row), you
can select the button using its class. For example:
$(".add-row").click(function() {...});
○ This selects the button with the class add-row and attaches a
click event to it.
4. Attribute Selectors:
○ Another selector method allows you to target elements by their
attributes. For example, selecting an input box by its type
(input[type="text"]) and applying a style change when it's
clicked.
5. Dynamic Table Management:
○ Once customer details are entered, you can dynamically update
the table.
○ After a certain number of entries (e.g., 5 customers), you may
want to hide the "Add Row" button to prevent further entries. This
can be achieved using the .hide() function, triggered after the
desired number of rows are added.
● ID Selector: $("#id")
● Class Selector: $(".class")
● Attribute Selector: [type="text"]
● Event Binding: .click(), .hide(), etc.
● this Keyword: Used to reference the current element.
This approach helps you dynamically interact with HTML elements and update
the DOM in response to user actions.
Types of Lists
Explanation
Example:
html
Copy code
<ol type="A">
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
</ol>
○
2. Unordered List (<ul>):
○ The style="list-style-type: value;" specifies the bullet
style:
■ disc (default).
■ circle for hollow circles.
■ square for filled squares.
■ none for no bullets.
Example:
html
Copy code
<ul style="list-style-type: square;">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
○
3. List Items (<li>):
○ Each item in the list must be enclosed in <li> tags.
○ Always close <li> tags for consistency and to avoid errors.
Concepts Overview
1. <iframe>:
○ The <iframe> element embeds one HTML document into
another.
○ Attributes include:
■ src: Specifies the URL of the document to embed.
■ name: Assigns a unique identifier to the iframe for use as a
target.
■ width and height: Define dimensions of the iframe.
2. Anchor Tags (<a>):
○ Used to create hyperlinks.
○ Key attributes:
■ href: Specifies the URL to navigate to or resource to load.
■ target: Specifies where to display the linked document:
■ _self: Default. Opens in the same frame.
■ _blank: Opens in a new tab or window.
■ _parent: Opens in the parent frame of the current
iframe.
■ _top: Opens in the full browser window, replacing all
frames.
■ Custom frame name: Opens the content in the
specified named frame.
Example Code
Key Points
1. Experiment with different target values to see how the linked content
is displayed.
2. Try nesting frames and observe how target="parent" and
target="top" behave.
3. Replace the src of the iframes dynamically using JavaScript for
advanced interactivity.
The alt (alternative text) attribute in the <img> tag is an essential feature in
HTML. It provides text-based information about the image and has several
uses. Here's a breakdown of its purpose and an example:
1. Accessibility:
○ Provides a description of the image for visually impaired users
who use screen readers.
○ Helps ensure that the content of your webpage is inclusive and
accessible.
2. Error Handling:
○ If the image fails to load due to a broken link, server issue, or typo
in the file path, the alt text will display instead, providing context
to the user.
3. SEO (Search Engine Optimization):
○ Search engines use alt text to understand the content of images
on your page.
○ It helps improve the page's visibility in search results, especially
in image-based queries.
4. Fallback for Text-Only Browsers:
○ In browsers or devices that do not support images, the alt text
acts as a substitute, maintaining the context of the content.
Example
Code
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Image with Alt Text</title>
</head>
<body>
<h1>Flower Gallery</h1>
<!-- Image with alt text -->
<img src="rose.jpg" alt="A beautiful rose flower with
red petals" width="300" height="200">
<p>The rose is a symbol of love and beauty.</p>
Output
Form Attributes
When creating a form, the <form> tag supports the following attributes:
1. action:
○ Specifies where the form's data should be sent after submission.
Example:
html
Copy code
<form action="welcome.html">
○
2. method:
○ Defines how the data should be sent. The options are:
■ GET: Appends the form data to the URL as query
parameters.
■ POST: Sends the data in the request body (preferred for
sensitive data).
Example:
html
Copy code
<form method="POST">
○
3. target:
○ Specifies where to display the response:
■ _self: Opens in the same tab (default).
■ _blank: Opens in a new tab.
■ _parent: Opens in the parent frame.
■ _top: Opens at the topmost window/frame.
Example:
html
Copy code
<form target="_blank">
○
4. autocomplete:
○ Enables or disables the browser's autocomplete feature.
Example:
html
Copy code
<form autocomplete="on">
○
The elements inside a <form> tag are known as form elements. Below are
some key ones:
1. Text Input
Example:
html
Copy code
<label for="fname">First Name:</label>
<input type="text" id="fname" name="firstname" required>
●
● Attributes:
○ type: Defines the input type (text, email, number, etc.).
○ id and name: For uniquely identifying and fetching the input data.
○ required: Ensures the field is mandatory.
Example:
html
Copy code
<fieldset>
<legend>Name</legend>
<label for="fname">First Name:</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lastname">
</fieldset>
●
3. Dropdown (<select> and <option>)
Example:
html
Copy code
<label for="flowers">Choose a flower:</label>
<select id="flowers" name="flowers">
<optgroup label="Favorite Flowers">
<option value="lily">Lily</option>
<option value="jasmine">Jasmine</option>
</optgroup>
<optgroup label="Others">
<option value="rose">Rose</option>
<option value="lotus">Lotus</option>
</optgroup>
</select>
4. Number Input
Example:
html
Copy code
<label for="rating">Rate us (1-5):</label>
<input type="number" id="rating" name="rating" min="1"
max="5">
5. Date Picker
Example:
html
Copy code
<label for="bday">Birthday:</label>
<input type="date" id="bday" name="birthday">
●
6. Email Input
Example:
html
Copy code
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
7. Telephone Input
Example:
html
Copy code
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone"
placeholder="123-456-7890"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" title="Format:
123-456-7890">
8. Textarea
Example:
html
Copy code
<label for="address">Address:</label>
<textarea id="address" name="address" rows="4"
cols="50"></textarea>
9. Submit Button
Example:
html
Copy code
<input type="submit" value="Submit">
● To associate labels with inputs, use the for attribute in the label and
the id attribute in the input.
Example:
html
Copy code
<label for="fname">First Name:</label>
<input type="text" id="fname" name="firstname">
Client-Side JavaScript:
● This updates the content of the HTML element with the ID demo.
Event Handling: JavaScript allows the handling of various user events like
mouse clicks, keyboard inputs, form submissions, etc. Example:
javascript
Copy code
document.getElementById("myButton").onclick = function()
{
alert("Button clicked!");
}
Server-Side JavaScript:
Server Handling: Node.js can handle HTTP requests, serve files, and interact
with databases. For example:
javascript
Copy code
const http = require('http');
server.listen(3000, () => {
console.log('Server running on port 3000');
});
○
● Event-Driven Model: Node.js operates on an event-driven,
non-blocking I/O model, making it lightweight and efficient for handling
numerous concurrent connections. It's particularly suitable for building
scalable network applications such as real-time chat apps or live
updates systems.
● Business Logic and Dynamic Content: On the server side, JavaScript
can implement business logic, handle form submissions, interact with
databases, and generate dynamic content. For example, a Node.js
server could process user data, store it in a database, and then send
back dynamic content or responses based on the user's actions.
In full-stack JavaScript applications, you can use Node.js for the server-side
logic and JavaScript (or frameworks like React, Angular, Vue.js) for the
client-side UI. For instance, a common pattern is using Express (a Node.js
framework) on the backend and React on the frontend to create seamless
applications.
Scripting Languages:
JavaScript Overview:
Advantages of JavaScript:
Variables in JavaScript:
JavaScript Functions:
● Conditional Statements:
○ If and if-else statements are used to execute code based on
conditions.
○ Switch: Used for multiple conditions where each case is
compared with the given expression.
● Loops:
○ For: Used for a known number of iterations.
○ While: Runs as long as the condition is true.
○ Do-While: Ensures the loop is executed at least once, then
checks the condition.
Conclusion:
This module will help you get a strong foundation in writing JavaScript code
that integrates with HTML, handles events, and manages data using
variables, functions, and control structures.
1. Functions in JavaScript
● Purpose of Functions: A function is a block of code designed to
perform a specific task. The advantage of using functions is reusability.
You can write a function once and call it multiple times with different
values (arguments).
● Defining a Function:
○ Use the function keyword, followed by the function name,
parentheses (), and curly braces {}.
○ The code inside the curly braces is what gets executed when the
function is called.
javascript
Copy code
function myFunction() {
// Code to execute
}
●
● Predefined vs. User-Defined Functions:
○ Predefined functions are already built-in in JavaScript (like
document.write() or console.log()).
○ User-defined functions are written by the programmer to
perform custom tasks.
● You can pass parameters to a function when calling it, and these
parameters can be used inside the function for calculations or other
operations.
Example:
javascript
Copy code
function multiply(a, b) {
return a * b;
}
let result = multiply(5, 10); // Calls the function with
arguments 5 and 10
console.log(result); // Output: 50
●
3. Return Keyword
javascript
Copy code
function add(a, b) {
return a + b;
}
let sum = add(3, 4); // sum = 7
4. Calling Functions
Example:
javascript
Copy code
function greet() {
console.log("Hello!");
}
greet(); // Calling the function
Global Variables: These are declared outside of any function and can be
accessed from anywhere in your code.
javascript
Copy code
let globalVar = 90; // Global variable
function displayVar() {
console.log(globalVar); // Accessible inside the
function
}
displayVar();
console.log(globalVar); // Accessible outside the
function as well
● If you try to access a local variable outside its scope (after the function
ends), JavaScript will throw a ReferenceError, as the variable
doesn't exist outside that function.
Example:
javascript
Copy code
function multiply() {
let result = 5 * 10; // Local variable
}
console.log(result); // Error: result is not defined
outside the function
7. Good Practices
● Modularizing Code: Functions help in modularizing your code.
Instead of writing the same logic multiple times, you write it once in a
function and reuse it.
● Naming Conventions: Choose meaningful names for your functions
and variables to make the code easier to understand and maintain.
html
Copy code
<button onclick="validateData()">Click me</button>
● Form Object
The form object in JavaScript represents an HTML <form> element. It
is used to access form elements (like text boxes, radio buttons, and
checkboxes) and manipulate them.
○ Accessing Form Elements: You can access form elements
using document.formName, document.forms[0], etc.
○ Form Methods:
■ reset(): Resets the form elements to their default values.
■ submit(): Submits the form programmatically.
Example:
html
Copy code
<form name="myForm">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit"
onclick="validateForm()">Submit</button>
</form>
6. Practical Implementation
Summary
○
● Navigator Object:
○ The navigator object provides information about the user's
browser (independent of the window object).
○ Properties: appName, appVersion, userAgent,
javaEnabled()
2. Document Object
○
● Form Object:
○ Forms in HTML are also part of the DOM and can be accessed
via document.forms.
You can retrieve or set the values of form fields using:
javascript
Copy code
document.myForm.username.value = "New User";
○
● Event Handling:
3. Cookie Handling
To create a cookie:
javascript
Copy code
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec
2024 12:00:00 UTC";
To read a cookie:
javascript
Copy code
console.log(document.cookie);
5. Practical Applications
Summary
1. Using getElementById:
○ You can access an HTML element by its unique id attribute using
document.getElementById("id").
Example:
javascript
Copy code
document.getElementById("demo").innerHTML = "Hello
World";
Example:
javascript
Copy code
var input = document.getElementsByTagName("input")[0]; //
Accessing the first input element
input.value = "New Value"; // Setting the value of the
input box
○
3. Using getElementsByClassName:
○ This method is useful for selecting elements with a specific class
name.
Example:
javascript
Copy code
var elements = document.getElementsByClassName("intro");
elements[0].innerHTML = "Updated Text"; // Accessing the
first element with class "intro"
○
4. Using querySelector:
○ The querySelector method allows you to select elements
using CSS selectors, which is more flexible.
Example:
javascript
Copy code
var element = document.querySelector("p.intro"); //
Accessing the first <p> element with class "intro"
Example:
javascript
Copy code
var form = document.forms["frm1"];
var firstName = form.elements["firstName"].value; //
Accessing first name from the form
○
2. Submitting Form Values:
○ After accessing form elements, you can read or modify their
values dynamically.
Example:
javascript
Copy code
alert("First Name: " + firstName + ", Last Name: " +
form.elements["lastName"].value);
Example:
javascript
Copy code
document.getElementById("p1").style.color = "blue"; //
Change text color to blue
document.getElementById("p1").style.fontSize = "20px"; //
Change font size
Example:
javascript
Copy code
document.getElementById("button1").onclick = function() {
alert("Button clicked!");
};
○
2. Using addEventListener:
○ You can use addEventListener to attach multiple events to an
element.
Example:
javascript
Copy code
var button = document.getElementById("myButton");
button.addEventListener("mouseover", function() {
alert("Mouse over the button!");
});
button.addEventListener("click", function() {
alert("Button clicked!");
});
button.addEventListener("mouseout", function() {
alert("Mouse out from the button!");
});
Conclusion:
1. HTML Setup:
○ You have a simple HTML page with a paragraph containing the
text: "Welcome to Google. Please visit Google Play Store."
○ You want to replace all occurrences of the word "Google" with
"Yahoo".
2. Accessing HTML Elements with JavaScript:
○ Use document.getElementById("para1").innerHTML to
access the content of the first paragraph (para1).
○ The text is stored in the STR variable.
3. Using the replace Method:
○ The replace() method in JavaScript is used to replace part of a
string with a new substring.
If you want to replace only the first occurrence of a word (like "Google"), you
can do:
javascript
Copy code
var text = str.replace("Google", "Yahoo");
○
4. Using Regular Expressions for Global Replacement:
○ The default replace() method only replaces the first
occurrence of a string. To replace all occurrences, you can use a
regular expression with the g modifier.
○ For a case-insensitive search, you can use the i modifier in
addition to g.
Example:
javascript
Copy code
var text = str.replace(/Google/gi, "Yahoo");
5. Here:
○ /Google/ is the regular expression that searches for the word
"Google".
○ g is the global flag, meaning it will replace all occurrences of
"Google".
○ i is the case-insensitive flag, so it will replace "Google", "google",
"GOOGLE", etc.
6. Displaying the Replaced Text:
Once the text is replaced, you update the content of the second paragraph
(para2) with the modified string:
javascript
Copy code
document.getElementById("para2").innerHTML = text;
○
7. Final Output:
After running the code, the text in the first paragraph changes from:
css
Copy code
Welcome to Google. Please visit Google Play Store.
To:
css
Copy code
Welcome to Yahoo. Please visit Yahoo Play Store.
Code Example:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Replace String Using Regular
Expression</title>
</head>
<body>
<p id="para1">Welcome to Google. Please visit Google
Play Store.</p>
<p id="para2"></p>
<script>
// Accessing the first paragraph content
var str =
document.getElementById("para1").innerHTML;
Explanation:
Example:
javascript
Copy code
var protocol = window.location.protocol;
document.getElementById("demo").innerHTML = "Protocol: "
+ protocol;
Example:
javascript
Copy code
var url = window.location.href;
console.log("Current URL: " + url);
Example:
javascript
Copy code
var screenWidth = screen.width;
var screenHeight = screen.height;
var availableWidth = screen.availWidth;
var availableHeight = screen.availHeight;
4.
5. Window Properties:
○ window.innerWidth: The inner width of the browser window
(including scrollbars).
○ window.innerHeight: The inner height of the browser window
(including scrollbars).
Example:
javascript
Copy code
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
6.
7. Navigating the Browser History:
○ history.back(): Moves the browser one step backward in the
session history (equivalent to the browser’s back button).
○ history.forward(): Moves the browser one step forward in
the session history (equivalent to the browser’s forward button).
Example:
javascript
Copy code
function goBack() {
history.back();
}
function goForward() {
history.forward();
}
8.
9. Navigator Object: The navigator object contains properties that
provide information about the browser:
○ navigator.appName: The name of the browser (e.g.,
Netscape).
○ navigator.appCodeName: The code name of the browser
(e.g., Mozilla).
○ navigator.platform: The platform on which the browser is
running (e.g., Win32, MacIntel).
Example:
javascript
Copy code
var appName = navigator.appName;
var appCodeName = navigator.appCodeName;
var platform = navigator.platform;
10.
Example Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>JavaScript BOM Demo</title>
</head>
<body>
<div id="demo"></div>
<script>
// Display the protocol (e.g., HTTPS)
var protocol = window.location.protocol;
document.getElementById("demo").innerHTML =
"Protocol: " + protocol;
function goForward() {
history.forward();
}
Summary:
Code Breakdown:
○
○ ReferenceError: This error happens when you reference a
variable that hasn't been declared or initialized in the scope.
■ Example: If you mistyped the variable name result,
JavaScript will throw a ReferenceError.
javascript
Copy code
var result = number1 * number2; // Correct spelling and
initialization
○ Fix: Verify that all variables are properly declared and initialized.
○ SyntaxError: Occurs when there is an issue with the code
syntax, such as missing parentheses, brackets, or semicolons.
■ Example: Forgetting to close a function or bracket can
result in a syntax error.
○ Fix: Ensure that all syntax is correct and complete.
○ RangeError: This error can occur if there's an issue like an
infinite loop, where the program doesn't reach an end condition.
Fix: Ensure that loops have correct termination conditions.
Using try-catch for Error Handling: The try-catch block helps you
catch errors without needing to open the browser's console. This is especially
useful when you want to display error messages directly on the webpage.
Example:
javascript
Copy code
try {
// Your code logic for multiplication
displayResult = multiply(num1, num2);
} catch (error) {
console.error(error); // Catch and display errors
document.getElementById("error").innerHTML =
error.message;
}
4.
○ try: Contains the code that might throw an error.
○ catch: Catches and handles the error, allowing you to display it
or take corrective actions.
5. Demonstration:
○ If an error is made (such as a reference error), the catch block
catches it and displays an error message on the webpage,
allowing the user to see where they made the mistake without
opening the browser's developer tools.
○ After identifying the mistake, you can correct it by reviewing the
code and ensuring that all method names, variable names, and
syntax are correct.
Example Code:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Multiplication Debugging</title>
</head>
<body>
<h1>Multiplication</h1>
<input type="number" id="number1" placeholder="Enter
first number">
<input type="number" id="number2" placeholder="Enter
second number">
<button onclick="display()">Multiply</button>
<div id="result"></div>
<div id="error" style="color: red;"></div>
<script>
function display() {
try {
var num1 =
document.getElementById("number1").value;
var num2 =
document.getElementById("number2").value;
if (num1 === "" || num2 === "") {
throw new Error("Please enter both
numbers.");
}
document.getElementById("error").innerHTML =
error.message;
}
}
Key Takeaways:
By understanding these error types and applying try-catch blocks, you can
write more robust JavaScript code and debug errors effectively in your web
applications.
In this jQuery Module Part One, you will be introduced to the fundamentals of
jQuery, its installation, and its usage in web development. The main focus of
the module is on understanding jQuery basics, using various selectors, and
performing HTML manipulations with jQuery.
1. What is jQuery?
● Lightweight and Fast: jQuery is fast because it minimizes the time for
server response by pushing content to the client side.
● Cross-Platform Compatibility: It supports multiple browsers, including
mobile devices and tablets, making it adaptable for various platforms.
● Extensibility: jQuery allows developers to extend its functionality
through plugins.
● SEO Friendly: It is search engine optimization (SEO) friendly and
works well with modern CSS3 features.
● Ease of Use: jQuery simplifies complex JavaScript tasks, making it
easier for developers to implement common functionalities like
animations, AJAX, etc.
● Local Installation:
○ Download the latest version of the jQuery script from jquery.com.
○ Use the <script> tag to link the downloaded jQuery file in your
HTML.
Example:
html
Copy code
<script src="path/to/jquery-3.6.0.min.js"></script>
○
● CDN-based Version:
○ Instead of downloading the file, you can link to a hosted jQuery
version from a CDN (Content Delivery Network). This method
improves loading speed and prevents the need for
re-downloading jQuery if a user has already visited a site using
the same CDN.
Example:
html
Copy code
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></scrip
t>
5. jQuery Selectors:
Selectors are used to target HTML elements that you want to manipulate with
jQuery. They are based on the $() function.
● Basic Selectors:
○
● Attribute Selectors:
You can also select elements based on their attributes, such as input fields of
type text.
javascript
Copy code
$("input[type='text']").css("background-color",
"yellow"); // Selects all input elements of type text.
○
● Empty Selector:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>jQuery Example</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></scrip
t>
</head>
<body>
<h1>Welcome to jQuery</h1>
<div id="myDiv" class="box">This is a div</div>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<script>
$(document).ready(function() {
$("p").css("color", "blue"); // Change color
of all paragraphs to blue
$("#myDiv").css("background-color", "pink");
// Change the background of div with ID 'myDiv' to pink
});
</script>
</body>
</html>
Summary:
jQuery Module Part Two, where you’ll learn how to effectively use jQuery to
manipulate DOM elements and attributes and handle user interactions
through events like mouse movements and keyboard inputs. Here's an outline
of the key points covered:
Example: Retrieving the value from a text box and displaying it:
javascript
Copy code
$("#showNameButton").click(function() {
var name = $("#nameBox").val();
alert("The name entered is: " + name);
});
2. Changing HTML Content Dynamically
javascript
Copy code
$("#addParagraphButton").click(function() {
$("p").append("<span>New Text</span>");
});
3. Removing Content
javascript
Copy code
$("#clearButton").click(function() {
$("#contentDiv").empty();
});
jQuery allows you to attach event handlers to various events like mouse
clicks, key presses, and form submissions.
Mouse Events:
Keyboard Events:
● keydown(), keypress(), keyup().
javascript
Copy code
$("p").mouseenter(function() {
$(this).css("background-color", "lightgray");
}).mouseleave(function() {
$(this).css("background-color", "lightblue");
}).click(function() {
$(this).css("background-color", "yellow");
});
javascript
Copy code
var keyCount = 0;
$(document).keydown(function() {
keyCount++;
$("#keyPressCount").text("Keys pressed: " +
keyCount);
});
javascript
Copy code
$("#removeHandlerButton").click(function() {
$("p").off("click");
});
7. Event Delegation
Event delegation is useful when you need to handle events for dynamically
added elements. This is done using the on() method with a selector.
javascript
Copy code
$("body").on("click", ".dynamicButton", function() {
alert("Button clicked!");
});
● selector: The jQuery selector for the element you want to target.
● speed: This can be slow, fast, or a time in milliseconds to define how
fast the slide transition will occur.
● easing: (Optional) The easing function to use for the transition (e.g.,
swing, linear).
● callback: (Optional) A function that will be executed once the
animation is complete.
Here’s an example of how you can use the slideToggle() method with a
button or any clickable element to trigger the sliding effect:
HTML
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Slide Toggle Example</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"></scrip
t>
<style>
#content {
width: 300px;
height: 100px;
background-color: #f1f1f1;
padding: 20px;
display: none;
}
</style>
</head>
<body>
<script>
$(document).ready(function(){
$("#toggleButton").click(function(){
$("#content").slideToggle("slow");
});
});
</script>
</body>
</html>
How It Works:
● When you click the "Click to Toggle" button, it will trigger the
slideToggle() method on the #content div.
● The slideToggle("slow") command will animate the visibility of the
#content div, sliding it down if it's hidden or sliding it up if it's visible.
Expected Outcome:
When you open this HTML file in your browser (e.g., Google Chrome), you'll
see:
Advanced Usage
You can adjust the animation speed, or add callback functions to perform
actions after the slide transition finishes. For example:
javascript
Copy code
$("#toggleButton").click(function(){
$("#content").slideToggle(500, function() {
alert("Slide transition complete!");
});
});
Here, 500 is the speed of the slide transition in milliseconds, and the callback
function will trigger an alert once the animation is complete.
Conclusion
In this demo, you are demonstrating how to use DOM manipulation in jQuery
to dynamically add, edit, or delete elements in an HTML page. This process
can be used in various scenarios, such as modifying a registration form where
input fields can be added based on user actions. Let's break down the key
steps:
You are working on a registration form where the user might need more than
one address field based on their input. For this example, you're adding more
input boxes dynamically when the user clicks a button (a "plus" button). Here’s
how you can implement this using jQuery:
Implementation Steps
1. HTML Structure:
You start with a basic HTML structure for the registration form:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>DOM Manipulation Example</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></scrip
t>
<style>
input {
margin: 5px;
}
</style>
</head>
<body>
<form id="registrationForm">
<div>
<label for="name">Name: </label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="address">Address: </label>
<input type="text" id="address"
name="address">
</div>
<button type="button" id="add">+</button>
</form>
<script>
$(document).ready(function(){
// When the "+" button is clicked
$("#add").click(function(){
// Insert a new input box before the "+"
button
$("#add").before('<div><label
for="address">Address: </label><input type="text"
name="address"></div>');
});
});
</script>
</body>
</html>
1. HTML Structure:
○ You have an initial form with a name field and an address field.
○ A "+" button is included that, when clicked, will add more
address input fields.
2. jQuery Script:
○ $(document).ready(function() {...});: Ensures that
the jQuery script runs after the DOM is fully loaded.
○ $("#add").click(function() {...});: Attaches a click
event listener to the button with the ID add. When this button is
clicked:
■ $("#add").before('<div><label
for="address">Address: </label><input
type="text" name="address"></div>');: This
adds a new address input field before the "+" button every
time it is clicked.
○ Each time the user clicks the button, a new address input field is
inserted above the button.
Expected Outcome:
● Initially, you have one name input field and one address input field.
● When the "+" button is clicked, an additional address input field is added
above the button. This allows users to dynamically add more input fields
as needed.
You can modify the script to implement other jQuery methods for different
effects, such as:
Conclusion:
This demo shows how to use jQuery to manipulate the DOM by dynamically
adding elements based on user interactions, like adding new input fields to a
form. By using methods like before(), append(), and prepend(), you can
create interactive, dynamic user interfaces that respond to user input and
simplify complex form creation or modification.
Objective:
The goal is to enhance a web page by adding animations and effects, making
it more interactive and engaging for users. Instead of having a static page,
jQuery allows you to add dynamic effects like sliding, fading, and toggling
elements.
Key Concepts:
1. jQuery Effects:
jQuery provides several built-in methods to add animations and effects
to HTML elements, enhancing user experience on a webpage. Some of
the most commonly used effects include:
○ Toggle: This effect hides or shows an element when clicked,
depending on its current state.
Example: $(selector).toggle();
○ Slide Up / Slide Down: These effects animate the hiding or
showing of an element with a sliding motion.
Example: $(selector).slideDown(); for showing and
$(selector).slideUp(); for hiding.
○ Fade In / Fade Out: These effects gradually change the visibility
of an element by fading in or out.
Example: $(selector).fadeIn(); or
$(selector).fadeOut();
○ Animate: This allows for custom animations by specifying CSS
properties.
Example: $(selector).animate({ opacity: 0.5 },
1000); (animates opacity to 50% over 1 second).
2. Implementing Toggle:
○ You can use the .toggle() method to hide or show content with
a single click. For example, a paragraph can disappear when
clicked and reappear on another click.
○ This action alternates between showing and hiding an element.
3. Slide Effect:
○ The Slide Down effect shows content with a smooth sliding
motion, which is visually different from the regular show/hide
toggle.
Example: $(selector).slideDown();
4. Custom Animations:
○ You can create custom animations using the .animate()
method, which modifies CSS properties like height, width, opacity,
and more. This allows for complex animations beyond the
predefined effects.
5. Use in Web Design:
○ Effects like these can be applied to various elements on the page,
such as menus, paragraphs, images, or navigation sections,
making the webpage more visually appealing and interactive.
● Toggle: $(selector).toggle();
● Slide Down / Slide Up: $(selector).slideDown(); /
$(selector).slideUp();
● Fade In / Fade Out: $(selector).fadeIn(); /
$(selector).fadeOut();
● Animate: Custom animations with .animate(), allowing you to modify
CSS properties.
Web Design Best Practices:
1. Target Audience:
○ The website should be designed keeping the target audience in
mind to ensure user satisfaction.
○ Prioritize customer needs and usability throughout the design.
2. Brand Consistency:
○ Use consistent brand logos, colors, and other visual elements
throughout the website.
○ Branding should be uniform to maintain a professional look.
3. Simplify Navigation:
○ The navigation should be simple, consistent, and easy for users
to find information.
○ Clear navigation contributes to better user experience and
website retention.
4. Responsive Design:
○ The website should work seamlessly across various devices and
screen sizes.
○ A responsive design ensures the website delivers a consistent
browsing experience.
5. Visuals Over Text:
○ Use visuals like images and graphics to engage users rather than
overwhelming them with too much text.
6. Social Media Integration:
○ Incorporate social media links to encourage interaction and allow
users to stay connected.
7. Call to Action (CTA):
○ Include clear and compelling CTAs to convert visitors into
customers. These buttons should stand out on the page.
8. SEO Best Practices:
○ Implement relevant SEO techniques such as using proper title
tags, header tags, meta descriptions, and short URLs to rank
higher in search engine results.
1. Robustness:
○ Code should handle errors gracefully and provide meaningful
error messages.
2. Portability:
○ Ensure the website or application works across different devices,
browsers, and screen resolutions.
3. Maintainability:
○ Code should be easy to modify and extend without affecting other
parts of the application.
4. Readability:
○ Code should be clear and understandable to others, making it
easier for developers to collaborate.
1. Consistent Formatting:
○ Write CSS in a clear, organized manner. Use a single line for
simple selectors, and group related styles together.
2. Use of Color:
○ Limit the number of colors in your color scheme, and ensure good
contrast between text and background for readability.
3. Clear Comments:
○ Add comments to your CSS code to explain complex logic or
sections of code.