There are two main ways JavaScript connects to HTML: the **`<script>`** element (covered in depth on its own page) for inline or external code, and **inline event-handler attributes** — `onclick`, `onchange`, `onsubmit`, and dozens more — written directly on an HTML element. While inline handlers still work, modern best practice strongly favors **unobtrusive JavaScript**: keeping all behavior in external `.js` files and attaching listeners with `addEventListener`, which cleanly separates structure (HTML) from behavior (JS) and avoids issues like Content Security Policy (CSP) restrictions that commonly block inline scripts/handlers for security.
1Understanding JavaScript in HTML
There are two main ways JavaScript connects to HTML: the `<script>` element (covered in depth on its own page) for inline or external code, and inline event-handler attributes — onclick, onchange, onsubmit, and dozens more — written directly on an HTML element. While inline handlers still work, modern best practice strongly favors unobtrusive JavaScript: keeping all behavior in external .js files and attaching listeners with addEventListener, which cleanly separates structure (HTML) from behavior (JS) and avoids issues like Content Security Policy (CSP) restrictions that commonly block inline scripts/handlers for security.
Many sites enforce a Content Security Policy (CSP) that blocks inline event handlers and inline <script> blocks entirely as an anti-XSS measure — code relying on onclick="..." attributes will silently fail to run on such sites.
<!-- Old style: inline handler -->
<button onclick="console.log('clicked')">Click me</button>2Practical Example
Here is a real-world application of JavaScript in HTML showing how it is used in production HTML.
<!-- Modern style: unobtrusive JavaScript -->
<button id="myBtn">Click me</button>
<script>
document.getElementById('myBtn').addEventListener('click', () => {
console.log('clicked');
});
</script>3Best Practices
Follow these guidelines when working with JavaScript in HTML:
1. Prefer addEventListener in an external script over inline onclick/onchange attributes
2. Keep HTML (structure) and JavaScript (behavior) in separate files for maintainability
3. Be aware that a strict CSP can block inline scripts/handlers entirely — unobtrusive JS avoids that problem altogether
Tip: Many sites enforce a Content Security Policy (CSP) that blocks inline event handlers and inline <script> blocks entirely as an anti-XSS measure — code relying on onclick="..." attributes will silently fail to run on such sites.
<!-- Old style: inline handler -->
<button onclick="console.log('clicked')">Click me</button>