0

I am trying to run a function from script.js when a user clicks on a paragraph but it gives me ReferenceError: stockClicked is not defined.

My HTML is:

<p id="stock" onclick="stockClicked()"></p>
<script type="module" src="script.js"></script>

And the stockClicked() function is define in script.js:

function stockClicked() {
  console.log("here");
}
8
  • 2
    you have double ""at your src. Commented Jan 23, 2019 at 17:46
  • sorry, mistake from when I wrote the question, doesn't change anything Commented Jan 23, 2019 at 17:49
  • 1
    You are including the script after your HTML element that uses it. It either needs to be before, or modified so it attaches the event to the element after the DOM has completed loading. Commented Jan 23, 2019 at 17:50
  • How would you modify it so it attaches after the DOM has loaded? Commented Jan 23, 2019 at 17:51
  • 1
    document.getElementById('stock').addEventListener('click', stockClicked) Commented Jan 23, 2019 at 17:56

2 Answers 2

3

When you reference a script with type="module", it gets loaded as an ES6 module, rather than in global scope. If you want stockClicked() to be available globally, just remove type="module" from the script tag.

If you really need to use type="module", then you have a couple of options:

  1. Create a new inline module script tag that imports from script.js and assigns the stockClicked() function to the global scope explicitly, by saying window.stockClicked = stockClicked.

  2. Add the click listener programmatically instead of in HTML. In other words, after the p tag, add an inline script that gets the element by id and adds a click listener. Something like this:

import {stockClicked} from './script.js';

document.getElementById("stock").addEventListener("click", stockClicked);

In both cases, you need to export the stockClicked() function from script.js. Also, it's recommended to name module files with .mjs instead of .js.

Sign up to request clarification or add additional context in comments.

3 Comments

I need the type=module because I'm importing a class into script.js and it won't work without it?
Edited the answer to include a couple of options.
This is a reasonable answer based on the code presented in the question.
2

If you need the type="module", then you have to bind the click event in the script itself

function stockClicked() {
  console.log('here');
}

document.getElementById('stock').addEventListener('click', stockClicked);
<p id="stock">click here</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.