0

Is it possible to call a function from an html file from a seperate JavaScript file? Currently I am trying to execute a function based on when a checkbox changes it's status.

The html looks something like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/style.css" type="text/css">
    <title>Title</title>
</head>
<body>
    <div class="grid-container">
        <div class="grid-1">
            <div class="sidebar">
                <h2>Item</h2>
                <input type="checkbox" id="item1" onchange="changeVis()" checked /> item1 <br />
                <input type="checkbox" id="item2" onchange="changeVis()" /> item2 <br />
            </div>
        </div>
    </div>
    <h2>Header 2</h2>
    <div id="map" class="map"></div>
    <script src="./index.js"></script>
        <script type="text/javascript">
            wangJangler();
        </script>
    <script>
        function changeVis() {
            console.log("hello world")
            wangJangler()
        }
    </script>
</body>
</html>

and the listeners and function wangJangler is in a seperate .js file and looks like this

document.getElementById("item1").addEventListener("change", changeVis());
document.getElementById("item2").addEventListener("change", changeVis());

function wangJangler() {
    console.log("WANGJANGLER");
}

The reason the function changeVis is in the html was for testing purposes. Ideally it would also be in the seperate javascript file. Is this even possible? Any help is appreciated. And apologies is the code is horrendously amateurish.

  • of course you can that is if you mean functions are defined in separate file and are then called by the HTML file. and her is great answer on this https://stackoverflow.com/a/11498131/10588650 – Syed May 31 '21 at 22:16
  • 1
    I found the reason for my errors, and it's quite elementary, so I apologize, but for anyone else looking who is newer to HTML and JavaScript if you declare/call any function in the HTML you must add anything related to it in the same file. Just don't reference it in the HTML file at all and keep everything in the separate .js file – Bryan A. Jun 03 '21 at 12:01

0 Answers0