0

I am trying to write a Google Apps Script that when published as a Web App will have a button, which when pressed, will call a function from Code.gs that will reveal or hide a piece of html (in effect, change the style of the div with a specific ID).

This is a small case example I've set up:

My index.html file:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>

<body>

  <button onclick="google.script.run.myFunction()">Click Me</button>

  <div id="myDIV">
    This is my DIV I want to Reveal/Hide.
  </div>

 </body>
</html>

My Code.gs file:

function doGet() {
  var template = HtmlService.createTemplateFromFile("index.html");
  var html = template.evaluate();
  return HtmlService.createHtmlOutput(html);
  }

function myFunction() {  
  var x = document.getElementById("myDIV");/*Where the Reference Error Shows Up*/
  if (x.style.display === "none") {
    x.style.display = "block";
    } 
    else {
      x.style.display = "none";
      }
   }

The error I keep getting when debugging is: ReferenceError: "document" is not defined. When published, the button appears with myDIV visible, and clicking the button does nothing.

I am assuming the problem is that I should not be using document.getElementByID(), but rather somethingelse.getElementByID(), but I don't know what that something else is. Most cases that I look for online are not specific to Google Web Apps. Any help would be appreciated.

1 Answer 1

1

You need to take care about where each code is executed : the GS code is executed on "server side" and so can't refer to document which is a navigator ("client side") variable.

Add myFunction() to your HTML and call it directly with onclick="myFunction();", that should do the trick.

Regards,

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.