Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to put JavaScript in HTML

JavaScript is an incredibly versatile and powerful programming language that has become an essential tool for web developers. It allows you to create dynamic and interactive websites by manipulating the HTML elements on your web page. If you are just starting to learn programming, you might be asking yourself, "How do I put JavaScript in HTML?" This blog post is designed to help you get started on your journey to becoming a JavaScript pro.

Getting Started with JavaScript in HTML

Before diving into JavaScript, let's make sure that you have a basic understanding of HTML. HTML, or HyperText Markup Language, is the standard language for creating web pages. It consists of a series of elements that are used to structure a web page and its content.

To include JavaScript in an HTML file, you'll need to use the <script> element. The <script> element is used to embed or reference a JavaScript file. You can either write your JavaScript code directly within the <script> element, or you can reference an external JavaScript file.

Here's an example of how to include JavaScript directly in your HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
</head>
<body>
  <h1>Welcome to My Web Page</h1>
  <p>Click the button below to see an alert.</p>
  <button onclick="showAlert()">Click me!</button>

  <script>
    function showAlert() {
      alert('Hello, world!');
    }
  </script>
</body>
</html>

In this example, we've created a simple web page with a button. When the button is clicked, the showAlert() function is called, which displays an alert box with the message "Hello, world!".

Now, let's look at an example of how to include an external JavaScript file in your HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
</head>
<body>
  <h1>Welcome to My Web Page</h1>
  <p>Click the button below to see an alert.</p>
  <button onclick="showAlert()">Click me!</button>

  <script src="myScript.js"></script>
</body>
</html>

In this example, we've removed the JavaScript code from the HTML file and placed it in an external file named myScript.js. The <script> element now includes a src attribute, which specifies the URL of the external JavaScript file. The contents of myScript.js would be:

function showAlert() {
  alert('Hello, world!');
}

Using an external JavaScript file is beneficial for several reasons:

  • It separates your HTML and JavaScript code, making it easier to maintain and debug.
  • It allows you to reuse the same JavaScript code across multiple HTML files.
  • It can improve the performance of your web page, as the browser can cache the external JavaScript file.

JavaScript Syntax and Basic Concepts

Now that you know how to include JavaScript in your HTML, let's explore some of the basic concepts and syntax of the language.

Variables

A variable is a container that holds a value. In JavaScript, you can declare a variable using the var, let, or const keyword:

var myVar = 10;       // Declares a variable named "myVar" and assigns it the value 10
let myLet = 20;       // Declares a block-scoped variable named "myLet" and assigns it the value 20
const myConst = 30;   // Declares a constant variable named "myConst" and assigns it the value 30

Variables can store different types of data, such as numbers, strings, and objects. Here are a few examples:

var num = 42;               // A number
var str = 'Hello, world!';  // A string
var obj = {                 // An object
  name: 'John',
  age: 30
};

Functions

A function is a block of code that performs a specific task. Functions can be defined using the function keyword, followed by the name of the function, a pair of parentheses, and a pair of curly braces:

function myFunction() {
  // Your code here
}

Functions can also take parameters and return values. Here's an example:

function addNumbers(a, b) {
  return a + b;
}

var sum = addNumbers(3, 4);  // Calls the function and stores the result (7) in the "sum" variable

Events

An event is an action or occurrence, such as a button click or a page load, that can trigger JavaScript code to be executed. You can use event listeners to attach functions to specific events. Here's an example of how to add an event listener for a button click:

<button id="myButton">Click me!</button>

<script>
  // Get the button element by its ID
  var button = document.getElementById('myButton');

  // Add a click event listener to the button
  button.addEventListener('click', function() {
    alert('Button clicked!');
  });
</script>

In this example, we first get a reference to the button element using document.getElementById(). Then, we use the addEventListener() method to attach a function to the button's click event.

Putting It All Together

Now that you have a basic understanding of JavaScript and how to include it in your HTML, let's create a simple web page that uses JavaScript to update the content of a paragraph element.

<!DOCTYPE html>
<html>
<head>
  <title>My Web Page</title>
</head>
<body>
  <h1>Welcome to My Web Page</h1>
  <p id="myParagraph">This is some text.</p>
  <button id="myButton">Change text</button>

  <script>
    // Get the paragraph and button elements by their IDs
    var paragraph = document.getElementById('myParagraph');
    var button = document.getElementById('myButton');

    // Add a click event listener to the button
    button.addEventListener('click', function() {
      paragraph.innerHTML = 'The text has been changed!';
    });
  </script>
</body>
</html>

In this example, we have a paragraph element with the ID "myParagraph" and a button element with the ID "myButton". When the button is clicked, the text inside the paragraph element is updated to "The text has been changed!".

This is just a simple example, but it demonstrates the power and flexibility of JavaScript for creating dynamic and interactive web pages. As you continue to learn and explore JavaScript, you'll discover many more ways to use the language to enhance your web projects. Happy coding!