JavaScript is used for making HTML web pages more interactive, and user-friendly. It is a scripting language that allows you to interact with certain elements on the page, based on user input. As with CSS, there are three major ways of including JavaScript:
- Inline:
You can add JavaScript to your HTML elements directly whenever a certain event occurs. We can add the JavaScript code using attributes of the HTML tags that support it. Here is an example that shows an alert with a message when the user clicks on it:
<button onclick=”alert(‘Click the Button!’);”>
Click!
</button>
- Script block:
You can define a script block anywhere on the HTML code, which will get executed as soon as the browser reaches that part of the document. This is why script blocks are usually added at the bottom of HTML documents.
<html>
<script>
var x = 1;
var y = 2;
var result = x + y;
alert(“X + Y is equal to ” + result);
</script>
</html>
- External JavaScript file:
You can also import the JavaScript code from a separate file and keep your HTML code clutter-free. This is especially useful if there is a large amount of scripting added to an HTML webpage.
<html>
<script src=”my-script.js”></script>
</html>
Leave a Reply