Adding JavaScript to HTML: A Beginner's Guide

Learn how to integrate JavaScript into your HTML pages to add interactivity. This tutorial covers basic JavaScript examples, demonstrating how to change content, styles, and attributes. It also explains the `<noscript>` tag for users with JavaScript disabled. Includes code snippets!



Adding JavaScript to HTML

JavaScript brings interactivity and dynamism to web pages. It allows you to create engaging user experiences beyond what's possible with static HTML.

A Simple JavaScript Example

Example: Displaying Date and Time

<button onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time
</button>
<p id="demo"></p>

This code adds a button that, when clicked, displays the current date and time in a paragraph with the id "demo".

What JavaScript Can Do

JavaScript significantly expands the capabilities of HTML. Here are a few key examples:

1. Changing Content

Example: Changing Content

document.getElementById("demo").innerHTML = "Hello JavaScript!";

This changes the inner HTML content of an element with the id "demo".

2. Changing Styles

Example: Changing Styles

document.getElementById("demo").style.fontSize = "25px";
document.getElementById("demo").style.color = "red";

This modifies the font size and color of an element.

3. Changing Attributes

Example: Changing Attributes

document.getElementById("image").src = "picture.gif";

This changes the src attribute of an image element.

The `<noscript>` Tag

The <noscript> tag provides alternative content for users with JavaScript disabled or browsers that don't support JavaScript. The content within is displayed only if JavaScript is not enabled.

Example: <noscript>

<noscript>
  <p>Sorry, your browser does not support JavaScript!</p>
</noscript>

Summary Table

Tag Description
<script> Contains JavaScript code.
<noscript> Provides alternative content if JavaScript is disabled.

For a comprehensive guide to JavaScript, visit our JavaScript Tutorial.