Getting Started with JavaScript
You can add JavaScript in three ways: internal/embedded, external, and inline.
You can add JavaScript directly within an HTML element using the onclick, onmouseover, and other event attributes.
<button onclick="console.log('Hello, World!')"> Click Me </button>html
- The JavaScript statement(s) run when the event (e.g.,
onclick) is triggered.
You can also write JavaScript inside the <script> tags, usually placed in the <head> or just before the closing </body> tag. This is the most common approach for adding JavaScript directly to an HTML document.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Internal JavaScript Example</title> <script> // This is the JavaScript code function showMessage() { alert('Hello from internal JavaScript!'); } </script></head><body> <button onclick="showMessage()">Click me</button></body></html>html
- It’s common to place JavaScript in a separate file and link it to your HTML. This makes your code more organized and reusable.
- This is the cleanest and most efficient method for adding JavaScript to a webpage, especially for larger projects.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>External JavaScript Example</title></head><body> <button onclick="showMessage()">Click me</button>
<!-- Linking the external JavaScript file --> <script src="script.js" type="text/javascript"></script></body></html>html
// script.jsfunction showMessage() { alert('Hello from external JavaScript!');}javascript
- Inline JavaScript: Use for simple interactions tied to specific elements (small snippets).
- Internal JavaScript: Ideal for small-to-medium projects or when you don’t want to manage multiple files.
- External JavaScript: Best for larger projects for maintainability and separation of concerns.