Basic HTML & CSS for JavaScript Integration
This document covers the fundamentals of HTML and CSS, their integration with JavaScript, and basic JavaScript functions, providing insights on how to create interactive web pages. It includes detailed explanations, scenarios, and examples to make the concepts clear and engaging for beginners.
Understanding HTML Basics
HTML, which stands for HyperText Markup Language, is the backbone of web development. It provides the structure of a web page by using a system of tags to define elements like headings, paragraphs, links, and more. HTML is the first language you'll learn if you're new to web development.
What is HTML?
HTML uses a structure that is easy to read and write, known as markup language. It is not a programming language but a set of instructions for how web browsers should render text, images, videos, and other types of content on a web page.
Structure of an HTML Document
A basic HTML document has a specific structure. Here is a simple example of what a basic HTML document looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p>This is a paragraph of text on my web page.</p>
</body>
</html>
Explanation of the code:
<!DOCTYPE html>
: This declaration defines the document type and version of HTML.<html lang="en">
: The<html>
tag is the root element of an HTML page. Thelang
attribute specifies the language of the document.<head>
: The<head>
section contains meta-information about the document, such as its character set, viewport settings, and the title.<meta charset="UTF-8">
: This tag specifies the character encoding for the HTML document, ensuring that special characters are properly displayed.<meta name="viewport" content="width=device-width, initial-scale=1.0">
: This tag ensures that the web page is responsive and displays correctly on different devices, such as desktops and mobile phones.<title>My First Web Page</title>
: This tag sets the title of the web page, which appears in the browser tab.<body>
: The<body>
section contains the content of the web page, which is visible to users.<h1>Welcome to My Web Page</h1>
: This tag defines a top-level heading on the page.<p>This is a paragraph of text on my web page.</p>
: This tag defines a paragraph of text.
Common HTML Tags
HTML uses various tags to format content. Here are some of the most common HTML tags:
<h1>
,<h2>
,<h3>
,<h4>
,<h5>
,<h6>
: Used to define headings.<h1>
is the highest level of heading.<p>
: Used to define a paragraph.<a href="url">
: Used to create hyperlinks to other web pages.<img src="image.jpg">
: Used to embed images on a web page.<div>
: Used to group elements for styling or scripting.<span>
: Used to style or script a part of a text.
Here’s an example using some of these tags:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Example</title>
</head>
<body>
<h1>My Web Page</h1>
<p>This is a paragraph <span style="color: blue;">with a blue word</span>.</p>
<a href="https://www.example.com">Visit Example.com</a>
<br>
<img src="image.jpg" alt="An example image">
<div>
<p>This is a paragraph inside a div.</p>
</div>
</body>
</html>
Explanation of the code:
<h1>
: Displays the main heading of the page, "My Web Page".<p>
: Displays a paragraph of text. Inside the paragraph, a<span>
tag is used to style a specific part of the text in blue.<a href="https://www.example.com">Visit Example.com</a>
: Creates a hyperlink to "Example.com".br
: Adds a line break.<img src="image.jpg" alt="An example image">
: Embeds an image on the page. Thesrc
attribute is the path to the image file, and thealt
attribute provides alternative text if the image cannot be loaded.<div>
: A container that holds a paragraph. While not visible by default, it is essential for styling and scripting.
Understanding CSS Basics
CSS, which stands for Cascading Style Sheets, is a language used to describe the look and feel of a web page. It complements HTML by providing the design and styling that make a web page visually appealing.
What is CSS?
CSS is a style sheet language used for describing the presentation of a document written in HTML or XML. It controls how elements are styled, positioned, and displayed on a web page.
Purpose of CSS
CSS helps in separating the content (HTML) from the presentation (CSS). By using CSS, developers can apply styles to multiple HTML elements, ensuring consistency across different parts of the website.
CSS Syntax
A CSS rule consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations (property and value pairs).
Selectors
Selectors are patterns used to select or group HTML elements for styling. Here are a few examples of selectors:
h1
: This selector targets all<h1>
elements..class
: This selector targets all elements with the class "class".#id
: This selector targets the element with the ID "id".
Properties
Properties define the styles that are applied to the selected elements. Common properties include color
, background-color
, font-size
, and more.
Values
Values are the settings of the properties. For example, the value of the color
property can be set to red
, #ff0000
, or rgb(255,0,0)
.
Here is a simple example of CSS:
/* This is a CSS comment */
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p {
font-family: Arial, sans-serif;
font-size: 16px;
color: darkblue;
}
Explanation of the code:
body { background-color: lightblue; }
: Sets the background color of the entire webpage to light blue.h1 { color: white; text-align: center; }
: Sets the text color of all<h1>
elements to white and aligns them to the center of the page.p { font-family: Arial, sans-serif; font-size: 16px; color: darkblue; }
: Sets the font family, font size, and text color for all<p>
elements.
Connecting HTML and CSS
Linking CSS to HTML
HTML and CSS can be linked in different ways to style HTML documents.
Internal Style Sheet
An internal style sheet is defined within the <head>
section of an HTML document using the <style>
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal CSS Example</title>
<style>
body {
background-color: lightgreen;
}
h1 {
color: darkgreen;
text-align: center;
}
p {
font-family: Verdana, sans-serif;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Welcome to the Internal CSS Example</h1>
<p>This paragraph uses internal CSS to change its style.</p>
</body>
</html>
Explanation of the code:
- The
<style>
tag within the<head>
section contains CSS rules that style the HTML elements.
External Style Sheet
An external style sheet is an external CSS file linked to an HTML document using the <link>
tag in the <head>
section. This is the most common method of linking CSS.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to the External CSS Example</h1>
<p>This paragraph uses external CSS to change its style.</p>
</body>
</html>
In the styles.css
file:
body {
background-color: lightgreen;
}
h1 {
color: darkgreen;
text-align: center;
}
p {
font-family: Verdana, sans-serif;
font-size: 18px;
}
Explanation of the code:
- The
<link>
tag in the<head>
section links the HTML document to the external CSS file namedstyles.css
.
Inline Styles
Inline styles apply CSS directly to HTML elements using the style
attribute within the HTML tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline CSS Example</title>
</head>
<body style="background-color: lightgreen;">
<h1 style="color: darkgreen; text-align: center;">Welcome to the Inline CSS Example</h1>
<p style="font-family: Verdana, sans-serif; font-size: 18px;">This paragraph uses inline CSS to change its style.</p>
</body>
</html>
Explanation of the code:
- The
style
attribute is used to apply styles to the<body>
,<h1>
, and<p>
elements directly.
Basic HTML Elements for JavaScript
Creating a Web Page
When creating a web page, you start with a basic HTML structure. Understanding the basic elements is crucial for interacting with JavaScript.
DOCTYPE Declaration
The <!DOCTYPE html>
declaration defines the document type and version of HTML. It helps in rendering the page correctly in different browsers.
HTML Tags
HTML tags are used to define elements in HTML. They are the building blocks of an HTML page.
Semantic HTML Elements
Semantic HTML elements provide meaning to the HTML document, making it more readable and accessible.
Header
The <header>
tag represents introductory content or a set of navigational links. It is used to define the header of a web page or section.
<header>
<h1>Website Title</h1>
<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
</header>
Explanation of the code:
- The
<header>
tag defines the header section of the webpage, containing a title and navigation links.
Main Content
The <main>
tag encapsulates the dominant content of the <body>
. It represents the main content area of a web page.
<main>
<h2>Main Content</h2>
<article>
<p>This is the main content of the page.</p>
</article>
</main>
Explanation of the code:
- The
<main>
tag contains the main content of the webpage, such as articles, news, or primary content areas.
Footer
The <footer>
tag represents the footer of a web page or section and typically contains information such as copyright data, contact information, or links to privacy policies.
<footer>
<p>© 2023 My Website</p>
<a href="mailto:info@example.com">Contact Us</a>
</footer>
Explanation of the code:
- The
<footer>
tag defines the footer section of the webpage, containing copyright and contact information.
Styling Elements with CSS
Basic CSS Properties
CSS properties define the appearance of HTML elements. Here are some essential CSS properties.
Text Properties
Properties like color
, font-family
, and font-size
control the appearance of text.
p {
color: green;
font-family: Times, serif;
font-size: 18px;
}
Explanation of the code:
color: green;
: Sets the text color of all<p>
elements to green.font-family: Times, serif;
: Sets the font family of all<p>
elements to Times, falling back to serif if Times is not available.font-size: 18px;
: Sets the font size of all<p>
elements to 18 pixels.
Color Properties
Properties like background-color
and color
control the colors of elements and their text.
body {
background-color: lightyellow;
}
h1 {
color: darkred;
}
Explanation of the code:
background-color: lightyellow;
: Sets the background color of the entire webpage to light yellow.color: darkred;
: Sets the text color of all<h1>
elements to dark red.
Layout Properties
Properties like width
, height
, and margin
control the layout of elements.
div {
width: 50%;
height: 200px;
margin: 20px;
background-color: lightblue;
}
Explanation of the code:
width: 50%;
: Sets the width of the<div>
to 50% of its containing element.height: 200px;
: Sets the height of the<div>
to 200 pixels.margin: 20px;
: Adds a 20-pixel margin around the<div>
.background-color: lightblue;
: Sets the background color of the<div>
to light blue.
CSS Classes and IDs
Classes and IDs are used to uniquely identify HTML elements for styling.
CSS Classes
Classes can be applied to multiple elements. They are defined with a period (.
) before the class name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Classes Example</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p class="highlight">This is a highlighted paragraph.</p>
<p>This is a paragraph without any class.</p>
</body>
</html>
Explanation of the code:
.highlight
: CSS class defined with thehighlight
class name.class="highlight"
: Applies the.highlight
class to the paragraph, changing its background color to yellow and making the text bold.
CSS IDs
IDs are intended to be unique within the HTML document. They are defined with a hash (#
) before the ID name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS IDs Example</title>
<style>
#main-header {
text-align: center;
color: navy;
}
</style>
</head>
<body>
<h1 id="main-header">Main Header</h1>
<p>This is a paragraph below the main header.</p>
</body>
</html>
Explanation of the code:
#main-header
: CSS ID defined with themain-header
ID name.id="main-header"
: Applies the#main-header
ID to the<h1>
element, centering the text and changing its color to navy.
Interacting with HTML using JavaScript
JavaScript is a programming language that can manipulate HTML elements dynamically. Interaction between HTML and JavaScript is essential for creating interactive web pages.
Accessing HTML Elements
JavaScript provides several methods to access HTML elements.
Document.getElementById
The document.getElementById
method returns the element with a specified ID.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>getElementById Example</title>
<script>
function changeText() {
document.getElementById("demo").textContent = "Text changed!";
}
</script>
</head>
<body>
<p id="demo">Original text.</p>
<button onclick="changeText()">Change Text</button>
</body>
</html>
Explanation of the code:
document.getElementById("demo").textContent
: Accesses the element with the IDdemo
and changes its text content to "Text changed!".<button onclick="changeText()">Change Text</button>
: A button that, when clicked, calls thechangeText
function.
Document.getElementsByClassName
The document.getElementsByClassName
method returns a collection of elements with a specified class name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>getElementsByClassName Example</title>
<style>
.highlight {
background-color: yellow;
}
</style>
<script>
function highlightBoxes() {
var elements = document.getElementsByClassName("highlight");
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "lime";
}
}
</script>
</head>
<body>
<p class="highlight">Box 1</p>
<p class="highlight">Box 2</p>
<button onclick="highlightBoxes()">Highlight Boxes</button>
</body>
</html>
Explanation of the code:
document.getElementsByClassName("highlight")
: Accesses all elements with the classhighlight
.- A loop iterates through the collection and changes the background color of each element to lime.
Document.getElementsByTagName
The document.getElementsByTagName
method returns a collection of elements with a specified tag name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>getElementsByTagName Example</title>
<script>
function changeAllParagraphs() {
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.fontWeight = "bold";
}
}
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<button onclick="changeAllParagraphs()">Make All Paragraphs Bold</button>
</body>
</html>
Explanation of the code:
document.getElementsByTagName("p")
: Accesses all<p>
elements.- A loop iterates through the collection and makes the text of each paragraph bold.
Manipulating HTML Elements
JavaScript can change the content, attributes, and styles of HTML elements.
Changing Content (textContent/innerHTML)
The textContent
and innerHTML
properties can change the content of an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>textContent Example</title>
<script>
function changeTextContent() {
document.getElementById("demo").textContent = "Text changed with textContent!";
}
function changeInnerHTML() {
document.getElementById("demo").innerHTML = "<strong>Text changed with innerHTML!</strong>";
}
</script>
</head>
<body>
<p id="demo">Original text.</p>
<button onclick="changeTextContent()">Change Text Content</button>
<button onclick="changeInnerHTML()">Change innerHTML</button>
</body>
</html>
Explanation of the code:
document.getElementById("demo").textContent
: Changes the text content of the element with the IDdemo
to "Text changed with textContent!".document.getElementById("demo").innerHTML
: Changes the inner HTML of the element with the IDdemo
to a bold text "Text changed with innerHTML!".
Changing Attributes (setAttribute)
The setAttribute
method sets the value of an attribute on a specified element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setAttribute Example</title>
<script>
function changeImage() {
document.getElementById("myImage").setAttribute("src", "new-image.jpg");
}
</script>
</head>
<body>
<img id="myImage" src="image.jpg" alt="An example image">
<br>
<button onclick="changeImage()">Change Image</button>
</body>
</html>
Explanation of the code:
document.getElementById("myImage").setAttribute("src", "new-image.jpg")
: Changes thesrc
attribute of the image with the IDmyImage
tonew-image.jpg
.
Changing Styles (style)
The style
property allows you to change the CSS style of an element directly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Style Property Example</title>
<script>
function changeStyle() {
document.getElementById("styledText").style.color = "orange";
document.getElementById("styledText").style.fontSize = "20px";
}
</script>
</head>
<body>
<p id="styledText">This text will change style.</p>
<button onclick="changeStyle()">Change Style</button>
</body>
</html>
Explanation of the code:
document.getElementById("styledText").style.color = "orange";
: Changes the color of the element with the IDstyledText
to orange.document.getElementById("styledText").style.fontSize = "20px";
: Changes the font size of the element with the IDstyledText
to 20 pixels.
Event Handling with JavaScript
Introduction to Events
Events are actions or occurrences in the web browser that generate data, such as mouse clicks or key presses. JavaScript can be used to respond to these events.
Common Events
Common events include onclick
, onmouseover
, onmouseout
, onkeydown
, and onload
.
Adding Event Listeners
Event listeners can be added to HTML elements to assign actions to be performed when specific events occur.
Inline Events
Inline events are added directly to HTML attributes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Event Example</title>
<style>
#demo {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
padding-top: 40px;
}
</style>
</head>
<body>
<div id="demo" onclick="this.style.backgroundColor='lightcoral'">Click me!</div>
</body>
</html>
Explanation of the code:
onclick="this.style.backgroundColor='lightcoral'"
: Changes the background color of thediv
element to light coral when clicked.
Event Listener Method
The addEventListener
method is a more modern way to add events. It is attached to elements and does not interfere with HTML attributes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Listener Example</title>
<style>
#demo {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
padding-top: 40px;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("demo").addEventListener("click", function() {
this.style.backgroundColor = "lightcoral";
});
});
</script>
</head>
<body>
<div id="demo">Click me!</div>
</body>
</html>
Explanation of the code:
document.addEventListener("DOMContentLoaded", function() {...})
: Ensures the script runs after the HTML document is fully loaded.document.getElementById("demo").addEventListener("click", function() {...})
: Adds a click event listener to the element with the IDdemo
.
Handling Event Objects
Event objects are passed to event handlers and provide information about the event.
Event Object Properties and Methods
Event objects have many properties and methods. Here are some common ones:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Object Example</title>
<style>
#demo {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
padding-top: 40px;
}
</style>
<script>
function showEventInfo(event) {
document.getElementById("info").textContent = "Mouse at (" + event.clientX + ", " + event.clientY + ")";
}
</script>
</head>
<body>
<div id="demo" onmousemove="showEventInfo(event)"></div>
<p id="info"></p>
</body>
</html>
Explanation of the code:
onmousemove="showEventInfo(event)"
: Calls theshowEventInfo
function whenever the mouse moves over the element with the IDdemo
.event.clientX
: Retrieves the horizontal coordinate of the mouse pointer.event.clientY
: Retrieves the vertical coordinate of the mouse pointer.
Basic JavaScript Functions
Functions in JavaScript are blocks of code designed to perform a particular task.
Understanding Functions
Functions can be defined and called to execute a block of code.
Defining Functions
Functions are defined using the function
keyword.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Definition Example</title>
<script>
function showMessage() {
alert("Hello, world!");
}
</script>
</head>
<body>
<button onclick="showMessage()">Show Message</button>
</body>
</html>
Explanation of the code:
function showMessage() { alert("Hello, world!"); }
: Defines a function namedshowMessage
that displays an alert.
Calling Functions
Functions are called to execute the code they contain.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Call Example</title>
<script>
function calculateArea(width, height) {
var area = width * height;
alert("Area: " + area);
return area;
}
</script>
</head>
<body>
<button onclick="calculateArea(10, 20)">Calculate Area</button>
</body>
</html>
Explanation of the code:
function calculateArea(width, height) { var area = width * height; alert("Area: " + area); return area; }
: Defines a function namedcalculateArea
that calculates the area of a rectangle and returns the result.
Parameters and Return Values
Functions can accept input values called parameters and can return values.
Function Parameters
Parameters are used to pass values into functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function Parameters Example</title>
<script>
function greet(name) {
alert("Hello, " + name + "!");
}
</script>
</head>
<body>
<button onclick="greet('Alice')">Greet Alice</button>
<button onclick="greet('Bob')">Greet Bob</button>
</body>
</html>
Explanation of the code:
function greet(name) { alert("Hello, " + name + "!"); }
: Defines a function namedgreet
that takes one parametername
and displays a greeting message.
Return Statement
The return
statement is used to return a value from a function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Return Statement Example</title>
<script>
function multiply(a, b) {
return a * b;
}
function displayResult() {
var result = multiply(5, 3);
document.getElementById("result").textContent = "Result: " + result;
}
</script>
</head>
<body>
<p id="result"></p>
<button onclick="displayResult()">Multiply 5 and 3</button>
</body>
</html>
Explanation of the code:
function multiply(a, b) { return a * b; }
: Defines a function that multiplies two numbers and returns the result.displayResult()
function callsmultiply(5, 3)
and displays the result in the paragraph with the IDresult
.
Debugging Basics
Debugging is the process of finding and fixing errors in code. It is an essential skill for developers to ensure that their web applications work as expected.
Console Log
The console.log
method is used to output messages to the console, helping you to understand the flow and values of your application.
Outputting Messages
console.log
can output messages, variables, or the entire objects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Console Log Example</title>
<script>
function logMessage() {
console.log("This is a message in the console.");
var name = "John";
console.log("Hello, " + name);
var person = { name: "Jane", age: 25 };
console.log(person);
}
</script>
</head>
<body>
<button onclick="logMessage()">Log Message</button>
</body>
</html>
Explanation of the code:
console.log("This is a message in the console.");
: Outputs a string message to the console.console.log("Hello, " + name);
: Outputs a personalized greeting message.console.log(person);
: Outputs theperson
object to the console.
Using Developer Tools
Most web browsers have built-in developer tools that can be used for debugging.
Inspecting Elements
Developer tools allow you to inspect the HTML elements and see their styles, structure, and attributes.
View Console Output
You can view the console output to see messages logged by console.log
.
In summary, HTML provides the structure of web pages, CSS is used for styling, and JavaScript allows interactivity and manipulation of the web page. By integrating these technologies, you can create rich and engaging web applications. Understanding the basics of HTML, CSS, and JavaScript is the foundation for building dynamic websites.