1. The <script>
Tag
Before diving deep into HTML, I'd like to introduce you to something cool — the JavaScript programming language.
JavaScript is a powerful programming language used to create dynamic and interactive web pages. It allows you to respond to user actions, change web page content, interact with servers, and do a ton of other stuff to make the user experience more enjoyable.
We won't be diving into JavaScript just yet, but sometimes I'll sprinkle it into examples. So let me quickly explain how JavaScript is integrated into an HTML document.
The <script>
tag is used for embedding JavaScript code into an HTML document.
<!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 my website!</h1>
<script>
// Your JavaScript code here
alert('Hello, world!');
</script>
</body>
</html>
In this example, the <script>
tag is used to embed simple JavaScript code that displays a popup with the message "Hello, world!".
2. Adding External Scripts
Sometimes it's better to keep JavaScript code in a separate file. This improves code organization and reusability. You can include a JavaScript file using the <script>
tag with the src
attribute to specify the name of the JavaScript file.
Including an external JavaScript file:
</h1>
<!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>
<script src="script.js" defer></script>
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>
This HTML file tells the browser to include a JavaScript file named script.js, which might contain the same code as in the example above:
// script.js:
// Your JavaScript code here
alert('Hello, world!');
The defer
attribute tells the browser to execute the script after the entire HTML document is fully loaded and displayed.
3. Inline JavaScript
Remember how we wrote CSS styles directly inside the style attribute of an element?
<p style="color:red"> Red</p>
We can do the same with JavaScript code.
Let's say we want an element to change its color to blue when clicked. Then we'd write code like this:
<p style="color:red" onclick="this.style.color = 'blue';">Red</p>
The green text is JavaScript code that gets executed when the user clicks on the <p>
element. Pretty simple, right?
-
onclick
: An HTML attribute that specifies a function to execute when the element is clicked. this
: Refers to the element that was clicked on.-
style.color
: A CSS property that changes the text color of an element.
GO TO FULL VERSION