Day 6: Introduction to JavaScript
Part 1: Basics of JavaScript
JavaScript is a versatile programming language that allows you to implement complex features on web pages. It can be used to update and change both HTML and CSS.
Adding JavaScript to HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Introduction to JavaScript</title>
</head>
<body>
<h1>Welcome to JavaScript</h1>
<p id="demo">This is a paragraph.</p>
<script>
document.getElementById("demo").innerHTML = "Hello, JavaScript!";
</script>
</body>
</html>
Part 2: JavaScript Syntax and Basics
Variables
Variables are containers for storing data values. You can declare a variable using var, let, or const.
let x = 5;
const y = 10;
var z = x + y;
Data Types
JavaScript variables can hold different data types: numbers, strings, objects, and more.
let name = "John"; // String
let age = 30; // Number
let isStudent = true; // Boolean
Operators
JavaScript uses arithmetic operators (+, -, *, /) to perform calculations.
let a = 10;
let b = 20;
let sum = a + b; // 30
Functions
Functions are blocks of code designed to perform a particular task.
function greet(name) {
return "Hello, " + name;
}
let greeting = greet("Alice");
console.log(greeting); // Hello, Alice
Part 3: Interacting with HTML and CSS
DOM Manipulation
JavaScript can access and change all the elements of an HTML document using the Document Object Model (DOM).
// Change the content of an element
document.getElementById("demo").innerHTML = "JavaScript is amazing!";
// Change the style of an element
document.getElementById("demo").style.color = "red";
Event Handling
JavaScript can respond to events like clicks, mouseovers, and form submissions.
<button onclick="changeText()">Click me</button>
<p id="demo">Original Text</p>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>
Part 4: Basic Examples
Alert Box
alert("Welcome to JavaScript!");
Console Log
console.log("This is a message in the console.");
Prompt Box
let user = prompt("Please enter your name:");
alert("Hello, " + user);
Part 5: Practice Exercise
Task: Create a simple webpage with a button. When the button is clicked, it should display an alert with a custom message.
HTML and JavaScript Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Practice</title>
</head>
<body>
<h1>JavaScript Practice</h1>
<button onclick="displayMessage()">Click me</button>
<script>
function displayMessage() {
alert("You clicked the button!");
}
</script>
</body>
</html>