I have a js function that hides an element on a page. I want to be able to call that function from a different js file. When I do a require it tells me document is not defined.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="picture1">
<img src="img.jpg" alt="img">
</div>
<script src="script.js"></script>
</body>
</html>
script.js:
function hide() {
var x = document.getElementById("picture1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
Want to call hide() function in here
main.js
const webHider = require("./script")
webHider.hider()
requireis not typically available inside a browser (it is usually used only in server side nodejs apps). Many functions will automatically get added to the "global" scope of the document when the file is loaded as a script tag. This means you can often find them inwindow.hidefor example. You might also want to post your web inspector console messages which will show what the actual error is. It is not always the case that they get added, sometimes libraries restrict how the function is defined to avoid polluting the window scope. Try callingwindow.hide()and see if it works.