aishwarya jain
aishwarya jain

Reputation: 19

Stop a js function from loading on initial page load

I am trying to stop a JS function from loading every time a page is loaded, i wanted it to work only when a button is clicked. I have tried using onclick and .addEventListener.On using onclick, the output data displays before clicking the load data button and on using .addEventListener no data loads even on clicking the button. Any help would be appreciated, Thank you!

<html>
<head>
    <title> Monitoring</title>
</head>
<body>
<div id="output"></div>
<script src="./lib/mam.web.min.js"></script>
<script>

    const TRYTE_ALPHABET = 'SFRRJJVGGYJI';

    const asciiToTrytes = (input) => {
      let trytes = '';
      for (let i = 0; i < input.length; i++) {
        var dec = input[i].charCodeAt(0);
        trytes += TRYTE_ALPHABET[dec % 27];
        trytes += TRYTE_ALPHABET[(dec - dec % 27) / 27];
      }
      return trytes;
    };

    const trytesToAscii = (trytes) => {
      let ascii = '';
      for (let i = 0; i < trytes.length; i += 2) {
        ascii += String.fromCharCode(TRYTE_ALPHABET.indexOf(trytes[i]) + TRYTE_ALPHABET.indexOf(trytes[i + 1]) * 27);
      }
      return ascii;
    };
    const outputHtml = document.querySelector("#output");
          const mode = 'public'
      const provider = ''

      const mamExplorerLink = ``

      // Initialise MAM State
      let mamState = Mam.init(provider)

      // Publish to tangle
      const publish = async packet => {
//      alert("coming into publish");
        // Create MAM Payload - STRING OF TRYTES
        const trytes = asciiToTrytes(JSON.stringify(packet))
        const message = Mam.create(mamState, trytes)
//      alert("p2");
        // Save new mamState
        mamState = message.state
//      alert("p3");
        // Attach the payload
        await Mam.attach(message.payload, message.address, 3, 9)
//        alert("p4");
        outputHtml.innerHTML += `Published: ${packet}<br/>`;
//      alert(message.root);
        return message.root
      }

      const publishAll = async () => {
//    alert("Yes 1.3");
        const root = await publish('ALICE')

        return root
      }

      // Callback used to pass data out of the fetch
      const logData = data => outputHtml.innerHTML += `Fetched and parsed ${JSON.parse(trytesToAscii(data))}<br/>`;
 (async function GKpublishAll(){
     const root = await publishAll();
    //  alert(root);
     outputHtml.innerHTML += `${root}`;

    })();

  </script>
  <form>
  Publish message :
  <input type="submit" onclick="GKpublishAll()">
</form>
</body>

</html>

Upvotes: 0

Views: 1341

Answers (3)

Ahmed Ayoub
Ahmed Ayoub

Reputation: 794

There are some unclear/uncertain/hidden parts of the code you posted. maybe you should start with a simplified version of it that shows the definitions and invocations.

for example, there is a function called logData you defined but never invoked/used. where should it be used, I didn't see any fetch here

@Ermir answer is the right answer for the question "why this piece of code works even without clicking the button?"

Upvotes: 0

naturecodevoid
naturecodevoid

Reputation: 36

On the <button> tag, you may want to add a attribute instead of adding a javascript event: mouseclick="function()". If it gives an error, try click="function()". Or try onclick="function()".

Hope it helps!

Upvotes: -1

Ermir
Ermir

Reputation: 1451

This piece of code defines and immediately calls the GKpublishAll function, if you don't want it called on page load, you should change the code from this:

 (async function GKpublishAll(){
 const root = await publishAll();
//  alert(root);
 outputHtml.innerHTML += `${root}`;

})();

to this:

 async function GKpublishAll(){
 const root = await publishAll();
//  alert(root);
 outputHtml.innerHTML += `${root}`;

}

Then, to use it when a button is clicked, you attach it to a button's onclick handlers like so:

<button onclick="GKpublishAll()">Click me</button>

Upvotes: 2

Related Questions