How to Create a Simple Hello World Webpage with HTML, CSS, and JavaScript
In this article, I'll show you how to create a simple HTML, CSS, and JavaScript webpage that displays the message "Hello, World!" and changes the color of the text every time the page is refreshed.
First, let's start with the HTML code. Create a new file called "index.html" and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1 id="hello-world">Hello, World!</h1>
</body>
</html>
This will create a basic HTML page with a title and a heading that says "Hello, World!".
Next, let's add some CSS to change the color of the text. Add the following code to the head
section of your HTML file:
<style>
#hello-world {
color: blue;
}
</style>
This code selects the h1
element with the id
of "hello-world" and sets its text color to blue.
Now, let's add some JavaScript to randomly change the color of the text every time the page is refreshed. Add the following code to the head
section of your HTML file, below the CSS:
<script>
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var helloWorld = document.getElementById('hello-world');
helloWorld.style.color = getRandomColor();
</script>
This code defines a function getRandomColor()
that generates a random color code using hexadecimal digits. It then selects the h1
element with the id
of "hello-world" and sets its text color to the randomly generated color.
Result:
That's it! Save your HTML file and open it in a web browser. You should see the "Hello, World!" heading in blue, and every time you refresh the page, the color of the text will change to a different random color.
I hope this article has been helpful in teaching you the basics of HTML, CSS, and JavaScript. Keep practicing and exploring, and you'll soon be able to create even more complex and dynamic web pages.