Home > Enterprise >  use function in html while importing js file as module
use function in html while importing js file as module

Time:08-02

So, I've seen this question kind of being answert. However in those cases, the one who asked had type="module" (while importing the javaScript file) and didn't mind to remove it. But I need to leave it module since I use import/export in other places. One recommendation was to import the JavaScript file twice, once with type=module and once without. that disabled my module import.

Is there a way to call a JavaScript function (in an onclick event listener) while importing my file as a module?

function drawAndMove(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    audi.draw();
    audi.move();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="module" src="compare.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <input type="text" value="nix" id="farbId">
    <button type="submit" id="subId" onclick="drawAndMove()">sub</button>

    <main>
        <canvas id="canvas" width="800" height="600">
        </canvas>
    </main> 

</body>
</html>

CodePudding user response:

Is there a way to call a JavaScript function (in an onclick event listener) while importing my file as a module?

Yes, but I would suggest that instead, you don't use an HTML onxyz-attribute style event handler. Instead, hook it up using modern event handling by doing this in the code that defines the drawAndMove function:

document.getElementById("subId").addEventListener("click", drawAndMove);

onxyz-attribute style event handlers have several issues, not least that the functions they call have to be globals (and of course, one of the many good things about modules is that they don't create globals by default). In constrast, using modern event handling works with non-globals.


But for completeness, to make it work in the way I don't recommend, make drawAndMove a global by assigning it to the window object in the code where it's defined: window.drawAndMove = drawAndMove;

But again: I don't recommend doing that.


Side note about your button element:

  1. It's not in a form, so there's no need for it to be a submit button. I'd suggest type="button" instead.
  2. The default for type is already "submit", so you never need to actually write type="submit" in a button element.
  • Related