JavaScript Intro
This section will learn about JavaScript Intro
JavaScript is one of the core technologies used in web development, alongside HTML and CSS. While HTML provides the structure of a webpage and CSS handles the styling, JavaScript is responsible for adding interactivity, allowing you to create dynamic and engaging user experiences.
What is JavaScript?
JavaScript is a programming language that runs in the browser. It enables you to create interactive features like form validation, sliders, modals, animations, and much more.
How JavaScript Works with HTML and CSS
- HTML (HyperText Markup Language): Defines the content and structure of the webpage. For example, headings, paragraphs, images, and forms.
- CSS (Cascading Style Sheets): Styles the HTML elements, controlling their appearance, such as colors, fonts, layouts, and spacing.
- JavaScript: Adds behavior to the webpage, making it interactive. It can manipulate the DOM (Document Object Model), respond to user events (like clicks and keyboard inputs), and fetch data from servers.
Adding JavaScript to Your Webpage
You can add JavaScript to your webpage in several ways:
- Inline JavaScript: Writing JavaScript directly within HTML elements. This is not recommended for larger projects.
<button onclick="alert('Hello, World!')">Click Me</button>
- Internal JavaScript: Including JavaScript inside a
<script>
tag within the HTML file.
<script>
function sayHello() {
alert('Hello, World!');
}
</script>
<button onclick="sayHello()">Click Me</button>
- External JavaScript: Linking an external JavaScript file to your HTML file. This is the best practice for keeping your code organized.
<!-- HTML File -->
<script src="script.js"></script>
// script.js
function sayHello() {
alert('Hello, World!');
}
example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interactive Webpage</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Welcome to My Interactive Webpage</h1>
<p id="message">Click the button to see the message!</p>
<button onclick="showMessage()">Show Message</button>
<script>
function showMessage() {
let messageElement = document.getElementById('message');
messageElement.innerText =
"Hello, you've learned the basics of JavaScript!";
}
</script>
</body>
</html>