5

I have this code

<div class="signup">
    <h2 class="form-title" id="signup"><span>or</span>Sign up</h2>
    <div class="form-holder">
        <input type="text" class="input" placeholder="Name" />
        <input type="email" class="input" placeholder="Email" />
        <input type="password" class="input" placeholder="Password" />
    </div>
    <button onclick="signup(this)" class="submit-btn">Sign up</button>
</div>
<script type="module" src="/libs/ajax.js"></script>
<script type="module" src="/scripts/login.js"></script>

No from the onclick here, I would like to call a function signup that is inside my login.js file

    import { Ajax } from '../libs/ajax.js'
    let signup = (e) =>{
        console.log(e)
    }

The problem is, I am using type="module" because I would like to import script within that js file. But, by assigning a type module, the function is not found from the html file. If I remove import and remove type="module" it does work.

Is there a way to bind a function from the onclick without assign my function to window. scope ?

3
  • don't create let signup, use function signup, functions hoists in javascript, meaning they don't need order of declaration, they are always on top Commented Aug 10, 2019 at 7:06
  • I tried let, I tried function, I tried export function signup they all don't work Commented Aug 10, 2019 at 7:07
  • The HTML5 placeholder attribute is not a substitute for the label element Commented Aug 10, 2019 at 7:19

1 Answer 1

7

Is there a way to bind a function from the onclick without assign my function to window. scope ?

No. Modules have their own scope. They don't create globals unless you do so explicitly.

Better to avoid using intrinsic event attributes in the first place. Bind your event handler from inside the module.

let signup = event => {
    console.log(event.currentTarget);
};
document.querySelector('button').addEventListener("click", signup)
Sign up to request clarification or add additional context in comments.

1 Comment

why is it better to avoid using intrinsic event attributes? Also I was wondering if the module is big and still hasnt loaded and the button has already been painted how would you handle this?

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.