OneBite.Dev - Coding blog in a bite size

link javascript to html and css

Code snippet for how to link javascript to html and css with sample and detail explanation

The integration of HTML, CSS, and JavaScript has evolved across times to open up new avenues in web designing. This article is designed to provide concise and beginner-friendly insights into linking JavaScript to HTML and CSS.

##Creating a HTML File

Before we begin with the process, you need to generate a HTML file. A simple HTML file can be created using the following code:

<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Hello Web Designers!</h1>
<button type="button" onclick="myFunction()">Click Me!</button>

<script src="script.js"></script>
</body>
</html>

Code Explanation for Creating a HTML File

Here is a step-by-step explanation for the HTML file code:

  • <!DOCTYPE html>: This declaration helps in defining the document type and version of HTML. In this case, it is HTML5.

  • <html>: It marks the beginning of the HTML document.

  • <head>: The head element contains meta-information about the HTML document.

  • <title>: This tag is used to insert a title for your webpage.

  • <link rel="stylesheet" type="text/css" href="styles.css">: This tag links the HTML file to the CSS file named ‘styles.css’ for styling purposes.

  • <body>: This tag represents the body of the HTML document.

  • <h1>: This tag represents the heading of the document.

  • <button type="button" onclick="myFunction()">Click Me!</button>: This is a button that, when clicked, will execute a JavaScript function named ‘myFunction’.

  • <script src="script.js"></script>: This tag links the HTML file to the JavaScript file named ‘script.js’. This script tag has been placed at the end so that it doesn’t block the rendering of the webpage and improves performance.

It is important to note that the CSS and JavaScript files should be located in the same directory as your HTML file for easy linkage. If they are located elsewhere, you would need to specify the correct path in the src and href attributes.

css