I have an HTML page with a js script in it. I have to place the script after the HTML (or load it after the page loading) because it needs an HTML tag to create a graph.
But I also need to export this graph with a button afterwards, but if my whole script is after the body, I can’t call the function because it doesn’t exist already. And if I pu the script before the body, the graph doesn’t have an html tag to be.
I don’t see how I could manage to make it work, if you have an idea I’m all for it.
I hope it’s clear, tell me if it’s not.
(Simplified code here, ask if you want whole code)
I tried this but the function is not defined.
<script type="text/javascript">
window.addEventListener("load", (event) => {
var graph = functionMakingAGraphAt("#balise");
myFunctionPrint() {
console.log(graph);
};
})
</script>
<body>
<div id="balise"></div>
<button onclick='myFunctionPrint()'></button>
</body>
I tried this but the graph var doesn’t exists.
<script type="text/javascript">
window.addEventListener("load", (event) => {
var graph = functionMakingAGraphAt("#balise");
})
myFunctionPrint() {
console.log(graph);
};
</script>
<body>
<div id="balise"></div>
<button onclick='myFunctionPrint()'></button>
</body>
I have to precise that I think I can’t access the generated graph html tag because it’s a jointjs library graph.
2
Answers
If your createGraph function is dependent on the readiness of specific HTML tags, you can still structure your code to ensure that the graph is created after those HTML tags are ready. Here’s an example:
In this example, the createGraph function checks if the required HTML tags (in this case, the container with the ID graphContainer) are ready before proceeding with creating the graph. If the container is not found, an error message is logged, and the function returns null. The exportGraph function then checks whether the graph data is available before proceeding with the export.
This ensures that the createGraph function is executed after the necessary HTML tags are ready, and you can export the graph data as needed. Adjust the code based on your specific requirements and the structure of your HTML document.
You can use unobtrusive event handling with
addEventListener
for all your events. You can put this event handler to run when the page is loaded too – this will mean that the graph variable can be in scope correctly.Also the est event to handle on the main window, to ensure everything in the page is ready for use before you execute any of this code is
DOMContentLoaded
.Demo: