user9273032
user9273032

Reputation:

Electron storing javascript functions

I have created a new electron application.

It consists of the following files:

index.html
main.js
renderer.js

In the index.html I have added a button with an onclick event:

<button onclick="myfunction()">Call Function</button>

And the function is just an alert for testing purposes:

myfunction() {
    alert('I am the js function');
}

My problem is that I've added the function code to both the renderer.js and to the bottom of main.js and when I click the button I see no alert.

How can I get js functions to be called from the index.html?

Upvotes: 1

Views: 37

Answers (1)

Purvil Bambharolia
Purvil Bambharolia

Reputation: 681

Let the myFunction reside in a separate javascript file. Let's say it's named "functions.js". To use this function in the HTML file (index.html), simply add the Javascript code using tag in the following manner -

<html>
  <body> 
  ...
  </body>
  <script type="text/javascript" src="./functions.js"></script>
</html>

Now, we will need to attach an onclick listener to the button that is rendered using the HTML code.

To do that, add the following in functions.js

document.getElementById('btn').addEventListener("click", function(){
    myFunction();
});

Upvotes: 1

Related Questions