JavaScript is a programming language that is used to implement functionalities and make websites interactive. JavaScript is also used to create and control Website contents and functions such as multimedia, animations and other functionalities.
We will cover how to incorporate JavaScript into a website as an in-line element and as a separate document.
Adding JavaScript to HTML Document.
If you want to add JavaScript to your Website as an in-line element, you can add it using the HTML tag <script>
just before the closing tag of the HTML body, this will ensure that the JavaScript code is applied where it is required.
Lets build a Website that displays the day's date when the h1 element is clicked on.
create an HTML document for the website and add an h1 element as follows:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
</head>
<body>
</body>
</html>
<h1> Click here to view today's date</h1>
Let's create a new variable in our JavaScript element and name it date
.
Assign this variable to the JavaScript's date method.
<script>
let date = new Date();
document.querySelector("h1").addEventListener("click", function (){
alert("Today's date is " + d )
});
</script>
Anytime the h1 element is clicked to view the date, an alert box will be triggered and the day's date would be alerted as shown below.
Adding JavaScript from a separate Javascript file
Large JavaScript files are best added to a project as an external file when they are used across several web pages. Separate JavaScript files are easier to maintain than in-line scripts so its more advisable to separate your JavaScript file from other components of the project.
To add your external JavaScript file to your website, create a new JavaScript file and name it script.js
and add it to the root of the project.
Add the JavaScript file to your HTML document by linking the file just before the closing tag of the body of the HTML document as shown below.
<script src="js/script.js"></script>
Conclusion
After all the steps above are followed, you should be able to add your JavaScript file to your website in anyway you feel comfortable with, you can now go ahead with your coding journey.
Cheers.
Top comments (0)