Displaying an external JavaScript function result on a HTML page

Hi!
Due to two languages being involved, I thought I’d make this post on the ‘general’ section.

I’ve written code in JS that I’ve tested and works fine. I want the result of the function in the external JS file to be displayed on a HTML page after a button is clicked that triggers the function.

I’ve searched for ways to do it and I think the best way is by using ‘inner.html’, but I’m struggling to implement it.

Here’s the code in the external JS file :

const items = ["Apples", "Bananas", "Sweets", "Elephants", "Giraffes", "Tables", "Pencils", "Parrots", "Chickens", "Cars", "Hats", "Chocolate Eggs", "Mops", "Baskets", "Frogs", "Rubies", "Sapphires", "Plant Pots", "Burgers"];
const quantity = Math.floor(Math.random() * 99) + 2;

function genMessage() {
	let item = items[Math.floor(Math.random() * items.length)];
	let shopMessage = "You need " + quantity + " " + item + ".";
	return shopMessage;
	document.getElementById('message').innerHTML = shopMessage;
}

When I use ‘console.log’ I get the result I need from the function so the function works.

This is my HTML code :

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Mixed Messages</title>
	<meta charset="utf-8">
	<script src="mixed_Messages_Code.js"></script>
</head>
<body>

	<header></header>
	<nav></nav>
	<main>
	<h1 id="message">Shopping List</h1>
	<button onclick="genMessage()">I forgot my shopping list, help!</button>
	</main>
	<footer></footer>

</body>
</html>

I want the ‘Shopping List’ element to change to the result of the function, which is stored in the variable ‘shopMessage’.

Thanks for taking the time to read!

Hi and welcome to the forums!

In your JS file, you have included the innerHTML line in the function. This would normally be fine, however you have placed it after the return statement. This means that this line is actually never being reached, as the function exits on a return statement and as such doesn’t run any code after it. If you move it up to be after the definition of shopMessage, but before the return statement, this should solve the issue.

1 Like

That’s fantastic, it works great now, thank you!

1 Like