HTML JavaScript


JavaScript is a programming language that is commonly used to add interactivity and dynamic behavior to web pages. It is one of the three core technologies of the World Wide Web, along with HTML and CSS. JavaScript is executed in web browsers and allows developers to manipulate the content, structure, and style of web pages.

Here are some key concepts and examples related to using JavaScript in HTML documents:

1. Inline JavaScript:

You can include JavaScript code directly within the HTML document using the <script> element. The <script> element can be placed in the <head> or <body> of the HTML document.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Inline JavaScript Example</title>
  <script>
    // JavaScript code here
    function showMessage() {
      alert('Hello, World!');
    }
  </script>
</head>
<body>

<button onclick="showMessage()">Click me</button>

</body>
</html>

2. External JavaScript:

You can also link to an external JavaScript file using the src attribute of the <script> element. This is a common practice for organizing and reusing JavaScript code.

<!-- External JavaScript file: script.js -->
// script.js
function showMessage() {
  alert('Hello, World!');
}

<!-- HTML file -->
<!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>
  <script src="script.js"></script>
</head>
<body>

<button onclick="showMessage()">Click me</button>

</body>
</html>

3. DOM Manipulation:

JavaScript is often used to manipulate the Document Object Model (DOM) of a web page. The DOM represents the structure of the document as a tree of objects, and JavaScript allows you to interact with and modify these objects.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>DOM Manipulation Example</title>
  <script>
    function changeText() {
      // Find the element with the id "demo" and change its text content
      document.getElementById('demo').innerHTML = 'Text has been changed!';
    }
  </script>
</head>
<body>

<p id="demo">This is some text.</p>
<button onclick="changeText()">Change Text</button>

</body>
</html>

4. Event Handling:

JavaScript is often used to respond to user interactions by handling events. In the example above, the onclick attribute is used to attach a JavaScript function to the click event of a button.

These are just a few basic examples, and JavaScript is a powerful and versatile language that can be used for a wide range of tasks, including form validation, AJAX requests, animations, and more. When using JavaScript in production, it's important to consider best practices and security considerations.

Post a Comment

Previous Post Next Post

Popular Items