OneBite.Dev - Coding blog in a bite size

link js to html and css

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

In this article, we will go through a brief and straightforward process of linking JavaScript (JS) to HTML and CSS. Incorporating these three web languages strengthens your web development skills, enhancing user interactivity, and facilitates better web designing.

Code Snippet: Linking JS to HTML

The first step in incorporating JS into your web project is to link it with a HTML file. You should use the <script> tag in the HTML file for this purpose. Let’s have a look at a simple example:

<!DOCTYPE html>
<html>
<head>
    <title>Web Page Title</title>
</html>
</head>
<body>
    <h1>Hello World!</h1>
    <script src="script.js"></script>
</body>
</html>

The script.js file contains all the JavaScript code that manipulates and adds interactivity to your webpage.

Code Explanation: Linking JS to HTML

In the example above, a HTML file was created, carrying the title “Web Page Title”. We also added an h1 tag, which displays the text “Hello World!“.

The <script> tag links the HTML file to a JavaScript file by adding src="script.js" ,where script.js is the name of the JavaScript file you want to link to the HTML file.

By placing the <script> tag right before the closing </body> tag, we ensure that the entire HTML document loads first before triggering the JS scripts. This practice decreases the chances of partial loading and enhances user experience.

Code Snippet: Linking JS to CSS

Linking JS to CSS can be achieved by involving JavaScript in manipulating CSS properties. First, ensure the CSS file is linked to HTML, and then manipulate the CSS using JS via DOM (Document Object Model).

Here’s a small instance:

<!DOCTYPE html>
<html>
<head>
    <title>Web Page Title</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <h1 id="title">Hello World!</h1>
    <script src="script.js"></script>
</body>
</html>

Here in script.js:

document.getElementById('title').style.color = 'red';

Code Explanation: Linking JS to CSS

In the given code, we must first link the CSS file to the HTML file using the <link> tag under the <head> tag. Now, styles.css is connected to your HTML file.

Next, without JavaScript, the color of the text “Hello World!” remains the same. To change it, we refer to the JavaScript file (script.js). In this file, we change the color of the h1 element to red by using the style object and the color property.

By doing so, the JavaScript file is linked with both the HTML and CSS files, allowing for dynamic, real-time changes for an enhanced user experience. Can’t wait to experiment? Take HTML, CSS, and JS files, and start creating the next big thing on the web!

css