In this tutorial, you will learn HTML JavaScript
JavaScript can be added to an HTML document in two ways:
- Inline Scripting: You can add JavaScript code directly within an HTML element using the “on*” attribute. For example, to create a button that displays an alert message when clicked, you can use the following code:
<button onclick="alert('Hello, World!')">Click me!</button>
- External Scripting: You can also link to an external JavaScript file using the “script” tag. For example, to link to an external JavaScript file called “script.js”, you can use the following code:
<script src="script.js"></script>
To use external scripting, you should put your script tag as close to the closing body tag as possible.
- In both cases, it is important to note that JavaScript code should be placed after the HTML elements it is supposed to affect, otherwise, it may not work as expected.
Here’s an example of an external script that would change the text of a button when it is clicked:
<!DOCTYPE html> <html> <head> <script src="script.js"></script> </head> <body> <button id="myButton">Click me!</button> </body> </html>
And here’s the content of the script.js file:
var button = document.getElementById("myButton"); button.onclick = function() { button.innerHTML = "I was clicked!"; };
n this example, the script.js file is linked to the HTML document using the “script” tag. The JavaScript code then uses the “getElementById” method to select the button element by its id and assigns an anonymous function to the “onclick” event. This function changes the button’s text to “I was clicked!” when it’s clicked.
JavaScript can also be used to manipulate HTML and CSS, create animations, validate forms, and perform other dynamic actions on a web page.
In summary, JavaScript can be added to an HTML document in two ways: inline scripting and external scripting. You can use the “on*” attribute to add JavaScript code directly within an HTML element, or you can link to an external JavaScript file using the “script” tag. It is important to note that JavaScript code should be placed after the HTML elements it is supposed to affect and you can use JavaScript to create interactive and dynamic websites.