1

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>
R.Lawrence
  • 25
  • 1
  • 4
  • As the other users have already answered, `location` is causing the error. There are some reserved words in JavaScript. You cannot use them as identifiers. See details: https://www.w3schools.com/js/js_reserved.asp – Miu Mar 10 '21 at 17:57

2 Answers2

3

The error message is

Uncaught SyntaxError: Identifier 'location' has already been declared

location already exists as a global variable that can't be re-declared, as window.location. Use a different variable name, like locations. (It's an array, after all, so it should probably be plural).

//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 locations = ['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(locations)

    //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 ' + locations[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>

I'd also highly recommend refactoring out the inline HTML attribute handlers and using addEventListener instead - it'll make the code more portable and will stop requiring global pollution for the script to work. Using that method, you'd be able to fix the problem a different way, by putting the whole script into an IIFE, so that the location you declared is not on the top level, thereby avoiding the error.

If the person array is dynamic, using innerHTML could be a security risk since that'll allow for arbitrary code execution, as the comment notes. Only use innerHTML when deliberately inserting or retrieving HTML markup. Otherwise, it's safer and more semantically appropriate to use .textContent, eg:

document.getElementById("mix").textContent = person[persName].name // ...
Stephen P
  • 14,422
  • 2
  • 43
  • 67
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Just do not use location since it is an existing global variable in the browser.

rename it to something else (I renamed it to location1) and it will work fine.

basically your script was having an error and that error keeps the script from loading.

//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 location1 = ['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(location1)

    //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 ' + location1[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>
Tiago Coelho
  • 5,023
  • 10
  • 17
  • yeah i have got it working now. thanks very much! now to try and get it to generate the message on everyclick... quick question: how did you know of the error? when I ran it no error was shown, but nothing happend on the click (the page loaded up fine). – R.Lawrence Mar 10 '21 at 18:12