Im having issues calling a function from a linked .js file. In my html file I have a button that has the onclick
set to call the function in the js file. Visual Studio tells me that the html and js files are linked correctly. Im using document.getElementById("id").innerHTML
in the js file to change some text in the html file, but to no avail!
There is a couple of similar questions on here, from which I have tried implementing the advice in my own code, but still no joy.
Any advice would be greatly appreciated.
Thanks in advance.
Note: the two functions being called are at the very bottom of the .js file. I have left all the other code in there in case something is causing the issue.
//Create array of objects
const person = [
{
name: 'Barry',
age: 99,
job: 'fisherman'},
{
name: 'Sally',
age: 89,
job: 'I.T. consultant'
},
{
name: 'Gary',
age: 79,
job: 'wrestler'
},
{
name: 'Mary',
age: 69,
job: 'political advisor'
}];
//Create Arrays
const weather = ['sunny.', 'raining.', 'hot.', 'cold.', 'overcast.', 'stormy.'];
const sport = ['tennis', 'football', 'snooker', 'golf', 'squash'];
const food = ['cakes', 'apples', 'pies', 'fish', 'biscuits', 'crisps'];
const location = ['beach', 'park', 'cliffs', 'wood', 'airport'];
//Generate random number between 0 and passed array length
const RandNumGen = (array) =>{
const num = Math.floor(Math.random()*array.length);
return num;
}
//Store random selection of each array in a variable
let w = RandNumGen(weather)
let s = RandNumGen(sport)
let f = RandNumGen(food)
let l = RandNumGen(location)
//Store random selection of age,job & name
let persName = RandNumGen(person);
let persAge = RandNumGen(person);
let persJob = RandNumGen(person);
//Function to generate random message
const mixMessage = () =>{
document.getElementById("mix").innerHTML = person[persName].name + ' who is ' + person[persAge].age + ' and is an expert ' + person[persJob].job + ', enjoys playing ' + sport[s] + ' and eating ' + food[f] + ' at the ' + location[l] + ' when it is ' + weather[w];
}
//mixMessage()
function test(){
document.getElementById("test").innerHTML = 'please work';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mixed Messages</title>
<script type="text/javascript" src="Main.js"></script>
</head>
<body>
<h1>Mixed Message Generator</h1>
<p id="test">TEST</p>
<button type="button" onclick="test()">TEST</button>
<p id="mix">MIX</p>
<button type="button" onclick="mixMessage()">Click me to generate a random message</button>
<footer id="footer">
Copyright me 2021
</footer>
</body>
</html>