0

I have the following class :

export default class Cursor {
    currentMode = modes.highlight
    //methods to modify currentMode
    toggleSelector = () => {
        this.currentMode = modes.selector
    }

which I then import and instantiate in my Index.js file:

import Cursor from './state.js'
const cursor = new Cursor(null)

I then load the index.js into my index.html file via:

<script type="module"src="./js/index.js"></script>

But when i try to use the object method as seen below:

<li><a class="btn-floating green" onClick='cursor.toggleSelector()'><i class="material-icons">done</i></a></li>

I have the following error:

cursor not defined

Is there a way to fix this?

Edit:

I have now done this as recommended but still does not work :

<script type="module" src="./js/index.js">import {cursor} from "./js/index.js";</script>

But still having this:

(index):27 Uncaught ReferenceError: cursor is not defined
at HTMLAnchorElement.onclick ((index):27)
15
  • Are you loading your index.js file at bottom of the html? If yes please move that in body section Commented Dec 19, 2020 at 13:41
  • type="module"src="./js/index.js" could you here make first between the two attributes a whitespace and try again? Commented Dec 19, 2020 at 13:45
  • Hey @VimalPatel yes it was at the bottom, i have shifted it to the body tag but doesn't work still Commented Dec 19, 2020 at 13:49
  • 1
    Does this answer your question? ES6 Modules: Undefined onclick function after import Commented Dec 19, 2020 at 13:50
  • 1
    This is now how scoping works with ES6 modules. Commented Dec 19, 2020 at 13:51

1 Answer 1

1

When you try to call onClick='cursor.toggleSelector()' , cursor object would be needed to be present in scope of the Window object.
The scope of module where cursor is defined is different .

try something like this in the index.js, it should work.
Basically, it is assigning cursor to the Window object , which allows to call from the HTMLAnchor element.

import Cursor from './state.js'
const cursor = new Cursor(null);
window.cursor = cursor;
Sign up to request clarification or add additional context in comments.

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.