How To Link Javascript To HTML, 3 Ways

by DM
how to link javascript to hmtl three ways

Are you wondering how to link JavaScript to HTML?

JavaScript makes websites dynamic by providing a means for a user to interact with elements on a webpage. When a user clicks on a button, it does something, and that something is defined by your JavaScript code.

Similar to CSS, there are three different ways to add JavaScript to your HTML document. In this post, we go over inline, internal, and external JavaScript.

Inline JavaScript

Remember how, for CSS, we add inline styles using the style attribute on HTML tags?

Read: 3 Ways You Can Add CSS To HTML

For JavaScript, the process is the same only, instead of the style attribute, you use the onclick attribute.

Onclick identifies the action (the part inside the quotations) that is to be executed when you click on that element.

Example: onclick = "alert('Hello World');"

<div>
<h2>Click the button to see what happens!</h2>          
<button type="button" onclick="alert('You just added inline JavaScript - you rock!');">Click me</button>
</div>
 
       * {
	    font-family: Arial, Helvetica, sans-serif;
	    background-color: linen;
	}

	div {
	    margin: 0 auto;
	    width: 500px;
	    text-align: center;
	    margin-top: 80px;
	}

	button {
	    padding: 15px 40px;
	    font-size: large;
	    margin-top: 20px;
	    border-radius: 10px;
	    border: none;
	    background: #E0B87B;
	    box-shadow: 0 0 8px lightsalmon;
	}

	button:hover {
	    background: #f3c886;
        }
inline javascript 1

Note: Double or Single Quotes


Notice the quotations – double quotes on the outside contain the action while single quotes on the inside contain the string to display.

You could have single quotes containing the action and double quotes containing the string.

‘alert(“Hello World”)’

But you can’t have two sets of double quotes or single quotes. Since the browser executes what’s between the quotes, it will take the second quotation to mean the end of the statement to execute.

So in “alert(“Hello World”)”, the browser considers the execution statement to be “alert(“ which yields an error.

double and single quotes in html 2

>> Tip <<

Use the Google inspect console tool to identify errors. JavaScript errors aren’t visible on the page-your code just won’t work and you won’t know why.

Right-click on the page you want to inspect – in this case, our button page – and choose Inspect.

how to open google inspect 3
Right-click and choose Inspect to bring up the dev console.

The dev console will pop up. From the menu bar, select Console to view JavaScript errors and warnings.

how to view javascript error 4
Select Console from the available list of dev console options.

Inline JavaScript is not recommended because it mixes JavaScript with HTML and, potentially, CSS making it difficult to manage and work with your scripts.

Remember that keeping languages separate is the best practice for producing clean, readable code.

Internal JavaScript

Internal JavaScript goes into the <body> by way of the script tags, <script></script>.

You might also see the script tags in the <head> of the document, though, it’s preferable to load JavaScript after your HTML and CSS.

Placing the script tags in the <body> towards the very end allows the browser to execute JavaScript after content and styles load.

It used to be good practice to declare the type of your script as text/javascript, but it’s no longer necessary.

Example:

<script type=”text/javascript”>alert(“Hello World”);</script>

<script type="text/JavaScript">

alert("You just added inline JavaScript - you rock!");

</script>

Notice that simply moving the alert we had inline inside the script tags will cause the alert to fire on load of the page. If you missed it, refresh the page.

Nothing happens when you click the button. That’s because we’re missing the “onclick” part.

To replicate the alert upon click of the button, you need to select the button element first from the document body.

document.getElementsByTagName(“button”)

Place the selected button into a variable so we can use it whenever we need to.

const button = document.querySelector(“button”);

Listen for the event type of “click” and perform certain actions when it happens within the callback function ( aka () => {…} ). In this case, the action is the alert message.

button.addEventListener("click",  () => {
alert("You just added inline JavaScript - you rock!");
});

You can, also, choose to skip saving the selected element into a variable.

document.querySelector("button").addEventListener("click",  () => {
    alert("You just added inline JavaScript - you rock!");
});
internal javascript 5
internal javascript 6

Note: We are using the most recent ES6 JavaScript syntax!

Internal JavaScript is much better than inline JavaScript when writing code. But, for long scripts, you’ll want to separate JavaScript from your HTML by including it in a separate, external file.

External JavaScript

To use external JavaScript, make an external file like you would do for an external CSS stylesheet only with the extension of “.js”.

Add your JavaScript code – what’s inside the script tags – into this file. Don’t add the script tags themselves, your code will break.

As you do with <img>, use the src attribute to specify the path of your .js file remembering the rules of file paths.

Example:

<script type=”text/javascript” src=”./myfile.js”></script>

<script type="text/JavaScript" src="./my-script.js"></script>

Place the script tag towards the end of the <body> to give the browser a chance to load the page before the JavaScript kicks in.

add external javascript to html 7
What your external JavaScript file should look like. No script tags!
add external javascript to html 8
Place your JavaScript files at the end of the <body> in your HTML document.

This is also how you would include external JavaScript from other sources that aren’t your own – just specify the provided file path in your src.

Note: There’s nothing between the open and closing script tags. That’s not a typo – script serves the sole purpose of loading the external JavaScript.

Related: 3 Ways You Can Add CSS To HTML

Related Posts