Not reading the function in a JavaScript Module file, by calling onclick in the html document

22 views Asked by At

Why when we call a function in 'onclick' in the html document, that function is not read in a JavaScript Module file if there is an 'import'?

Is there a solution to use 'onclick' again in this case?

For example, 'onclick' calls the following:

<input type="button" value="-" class="dark" onclick="mathfa('-')">

This function:

function mathfa(ma) {
    if (ma == "Percent") {
        varable.po = false;
        varable.eva = false;
        varable.per = true;
        if (varable.box.value.indexOf("^") == -1
            && varable.box.value.indexOf("+") == -1
            && varable.box.value.indexOf("-") == -1
            && varable.box.value.indexOf("*") == -1
            && varable.box.value.indexOf("/") == -1
            && varable.box.value.indexOf("%") == -1) {
            varable.box.value += "%*";
        } else {
            varable.box.value = varable.box2.value + "%*";
        }

    } else if (ma == 'pow') {
        per = false;
        eva = false;
        po = true;
        if (varable.box.value.indexOf("^") == -1
            && varable.box.value.indexOf("+") == -1
            && varable.box.value.indexOf("-") == -1
            && varable.box.value.indexOf("*") == -1
            && varable.box.value.indexOf("/") == -1
            && varable.box.value.indexOf("%") == -1) {
            varable.box.value += "^";
        } else {
            varable.box.value = varable.box2.value + "^";
        }
    } else {
        varable.po = false;
        varable.per = false;
        varable.eva = true;
        varable.box.value += ma;
    }
}

In a JavaScript Module file: <script type="module" src="http://localhost:8080/scripts/script.js"></script>

I even put this function in another file and imported it in the main JavaScript file, but it didn't work. In addition, I know that if I call that function by 'addeventlistener', it works, but as I mentioned, my problem is using 'onclick'.

1

There are 1 answers

0
Ali Nasiri On

Using "onclick" requires the function to be a property of the global (window) object. You can add window.mathfa = mathfa; to the module.

Using .addEventListener() is generally considered better however, as it's more flexible.