HTML JavaScript

Master webpage interactivity and behavioral programming through JavaScript integration techniques

JavaScript transforms static documents into responsive, engaging interfaces. This scripting language manipulates document content, element properties, visual presentation, and processes user interactions. The <script> element embeds client-executed code within HTML structures.

What is JavaScript?

JavaScript is the world's most popular programming language. It is the programming language of the Web.

  • JavaScript can change HTML content
  • JavaScript can change HTML attribute values
  • JavaScript can change HTML styles (CSS)
  • JavaScript can hide or show HTML elements
  • JavaScript can validate form data
  • JavaScript runs in the browser (client-side)

The HTML <script> Tag

The HTML <script> tag is used to define a client-side script (JavaScript).

The <script> element either contains script statements, or it points to an external script file through the src attribute.

Example - Inline JavaScript

<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":

Example

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>
Click Me!
</button>

</body>
</html>

Explanation:

When you click the button, JavaScript changes the content of the paragraph with id="demo".

Try it Yourself ›

Click the button below to open this example in our interactive editor:

Try it Yourself ›

JavaScript Can Change HTML Attribute Values

In this example, JavaScript changes the value of the src attribute of an <img> tag:

Example - Change Image

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">
Turn on the light
</button>

<img id="myImage" src="pic_bulboff.gif" alt="Light bulb">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">
Turn off the light
</button>

How it works:

The buttons change the src attribute of the image, switching between two different images.

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element is a variant of changing an HTML attribute:

Example - Change Font Size

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">
Click Me!
</button>

Example - Change Color

<p id="demo">JavaScript can change the color of text.</p>

<button type="button" onclick="document.getElementById('demo').style.color='red'">
Click Me!
</button>

JavaScript Can Hide/Show HTML Elements

Hiding HTML elements can be done by changing the display style:

Example - Hide Element

<p id="demo">This is some text.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">
Hide Text
</button>

Example - Show Element

<p id="demo" style="display:none">This is some text.</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">
Show Text
</button>

Where to Place JavaScript

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>JavaScript in Head</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

JavaScript in <body>

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript in Body</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

💡 Best Practice

Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.

External JavaScript

Scripts can also be placed in external files. External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src attribute of a <script> tag:

Example

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

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

Example - myScript.js

function myFunction() {
    document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External JavaScript Advantages

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads
  • You can use the same script on multiple pages

Note: External scripts cannot contain <script> tags.

External References

An external script can be referenced in 3 different ways:

📁 Full URL (Absolute Path)

<script src="https://www.example.com/js/myScript.js"></script>

📂 File Path (Relative Path)

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

📄 Same Folder

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

The <noscript> Tag

The HTML <noscript> tag defines an alternate content to be displayed to users that have disabled scripts in their browser or have a browser that doesn't support scripts:

Example

<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>

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

Accessibility Note:

The <noscript> tag is important for accessibility, providing fallback content for users who have JavaScript disabled or unavailable.

Common Script Tag Attributes

Attribute Description
src Specifies the URL of an external script file
type Specifies the media type of the script (optional in HTML5)
async Specifies that the script is downloaded in parallel and executed as soon as available
defer Specifies that the script is executed after the page has finished parsing
crossorigin Sets the CORS settings for the script

Async and Defer Attributes

The async and defer attributes are boolean attributes used to control how external scripts are loaded and executed:

Example - Async

<script src="myScript.js" async></script>

Async:

The script is downloaded in parallel to parsing the page, and executed as soon as it's available (may be before parsing completes).

Example - Defer

<script src="myScript.js" defer></script>

Defer:

The script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.

⚡ Use async when:

  • The script is independent (doesn't depend on other scripts)
  • Order of execution doesn't matter
  • Example: Analytics scripts, ads

⏱️ Use defer when:

  • The script depends on the DOM being ready
  • Order of execution matters
  • Example: UI libraries, frameworks

JavaScript Best Practices

  • Place scripts at the bottom: Put scripts before the closing </body> tag for better performance
  • Use external files: Keep JavaScript in separate .js files for better maintainability
  • Use async/defer: Optimize loading with async or defer attributes for external scripts
  • Minimize inline scripts: Avoid using onclick and other inline event handlers when possible
  • Provide noscript fallback: Use <noscript> for users without JavaScript
  • Use strict mode: Add "use strict"; at the beginning of your scripts
  • Comment your code: Add comments to explain complex logic
  • Validate user input: Always validate and sanitize user input on both client and server

Security Considerations

⚠️ Important Security Notes

  • Never trust user input: Always validate and sanitize data from users
  • Avoid eval(): Never use eval() with user input as it can execute malicious code
  • Use HTTPS: Always load external scripts over HTTPS to prevent tampering
  • Content Security Policy: Implement CSP headers to control script sources
  • Keep libraries updated: Regularly update JavaScript libraries to patch security vulnerabilities

Test Your Knowledge