Convert JavaScript code to Google Appscript

Looking for guidance on incorporating Javascript code into my Google Appscript. Here is the code snippet: I have a separate Stylesheet.html file saved. Can someone advise me on how to invoke the functions within the html file?

<script>
  //google.script.run.updateColors();
  
  
  document.querySelectorAll("input[type='number'], input[type='range']").forEach(doStuff);
  
  function doStuff(){
    google.script.run.withSuccessHandler( {
    this.addEventListener("input", function() {
    if (this.type === "range") {
      this.nextElementSibling.value = this.value;
    } else if (this.type === "number") {
      this.previousElementSibling.value = this.value;
    }

  }
    }).updateColors();


  }

  

  
  function updateColors() {
 
  google.script.run.withSuccessHandler({ 
     const colorFront = [ 
    document.querySelector("#color-1-r").value,
    document.querySelector("#color-1-g").value,
    document.querySelector("#color-1-b").value
  ];
  const colorBack = [
    document.querySelector("#color-2-r").value,
    document.querySelector("#color-2-g").value,
    document.querySelector("#color-2-b").value
  ];
  } ).updateDemoColors(colorFront, colorBack).updateBoxesColors(colorFront, colorBack).updateHex(colorFront,colorBack);
  
  }

  function updateHex(colorFront, colorBack) {
    google.script.run.withSuccessHandler(  {
  const colorFrontHex = colorFront.map(function(el) { return Number(el).toString(16).padStart(2, "0").toUpperCase(); });
  const colorBackHex = colorBack.map(function(el) { return Number(el).toString(16).padStart(2, "0").toUpperCase(); });
  document.querySelector("#color-1-hex").value = `#${colorFrontHex.join('')}`;
  document.querySelector("#color-2-hex").value = `#${colorBackHex.join('')}`
  }); 
    
  }

  function updateBoxesColors(colorFront, colorBack) {

    google.script.run.withSuccessHandler(ratio => {
    const ratio = contrast(colorFront, colorBack);
    document.querySelector("#aa-normal").className  = ratio < 0.22222 ? "" : "fail";
    document.querySelector("#aa-large").className   = ratio < 0.33333 ? "" : "fail";
    document.querySelector("#aaa-normal").className = ratio < 0.14285 ? "" : "fail";
    document.querySelector("#aaa-large").className  = ratio < 0.22222 ? "" : "fail";

    const totalWrong = document.querySelectorAll(".fail").length;
    let mouth = document.querySelector("#mouth");
    let smile = document.querySelector("#smile");

    switch(totalWrong) {
      case 0:
        mouth.setAttribute("d", "M 106,132 C 113,127 125,128 125,132 125,128 137,12...
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <?!= include('Stylesheet'); ?>
  </head>
  <body>
    
    <section id="color-contrast">
  <h1>Google Color Contrast Checker</h1>
  <div class="character">
    <div id="jill">
    <svg width="250" height="250" viewBox="0 0 250 250" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title  desc">
    <title id="title">Contrast Checker</title>
    <desc id="desc">Cartoon of a Caucasian woman smiling, and wearing black glasses and a purple shirt with white collar.</desc>
    <defs>
      <clipPath id="scene">
        <circle cx="125" cy="125" r="115"/>
...      

Seeking advice on integrating Javascript code into Google Appscript. I have a separate Stylesheet.html file saved and need help with invoking the functions within it.

If anyone has suggestions on modifying this for Google Appscript, I'd greatly appreciate it.

Answer №1

Summary

If you need to execute an Apps Script function from your HTML file, you must utilize the google.script.run client-side JavaScript API call.

To invoke the contrast function located in Code.gs, you should include the following code in your Page.html file:

<script>
    google.script.run.contrast();
</script>

Explanation

It is important to note that functions on the client side (like Code.gs in this scenario) must adhere to Apps Script conventions - meaning, it is not possible to access DOM elements, such as document.

If you wish to keep using your existing functions, you will need to integrate them into your HTML file and restrict the Apps Script code to only calling the doGet function.

Resource

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React Hook Form for Interactive Slider and User Input Controls

Whenever I move the Slider, I want to retrieve the same value as when I enter a new value in the Input field. However, the current setup is not functioning correctly. <StyledSlider {register(NAME ...

Communication between child and parent components in Vue.js is an essential feature

Attempting to invoke functions from my component to Vue for the login process. This is the code snippet of my component : Vue.component('auths', { data: function() { return { ip: '', sessiontoken: '' } ...

What is the best way to adjust the placement of this object so it is anchored to the left side?

I'm struggling to position one of my divs more to the left within a flex container. No matter what I try, changing the class of the div doesn't seem to have any effect. Here's the code snippet: import React from 'react' import &apo ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

AngularJS modules are not loading dependencies such as constants or controllers

While searching for the reason why a properly defined factory is not loading, I came across this question. This led me to contemplate on the concept of services being "defined in an angular module". Consider this example: angular.module('d3', ...

What is the best approach to synchronize checkboxes with boolean values in my data model?

I've spent hours searching through similar questions, but haven't found a solution that perfectly matches my issue. What I need is to have a checkbox automatically checked based on a true/false value in my data using data binding. While I can suc ...

Identifying Browsers using CSS

I am struggling to understand why my HTML5 website appears differently in each browser. It seems like a CSS issue, but I can't pinpoint the exact problem. Here are screenshots of how the site looks on different browsers: Chrome: Safari: Internet E ...

Ways to make two blocks of text appear side by side and adapt to different screen sizes

Check out our website imageI'm facing a challenge in making these two text elements appear next to each other rather than stacking on top of each other. Additionally, I need them to adapt responsively to changes in screen size. When 'Icontext&ap ...

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

Having trouble with nested confirm pop ups?

I am attempting to show an additional confirmation pop-up when the YES button is clicked, but it doesn't seem to be working. Here's my code: $.confirm({ text: "Are you sure you want to delete ?", confirm: function() { $.confirm( ...

Resizable vector graphics with consistent border dimensions

I need a solution that maintains a constant line width while still making the SVG responsive. Here is the desired outcome: https://codepen.io/dudleystorey/pen/wMLBLK The example linked above achieves this using CSS, but I am looking to achieve the same r ...

Responsive SmoothSlider

Need help fixing the responsive breadcrumbs in my slick slider. The slick-content-slider is taking a strange height and I want to ensure that every div remains on the same line. Thank you in advance! $('.slick-content-slider').slick({ slides ...

How can I use jQuery to either display or hide the "#" value in a URL?

I have a question that I need help with. Let's say I have the following links: <a href="#test1"> Test </a> <a href="#test2"> Test 2 </a> When I click on Test, the URL will change to something like siteurl/#test1. However, whe ...

Change the body selector in CssResource to apply custom styles

I have implemented a CssResource within a ClientBundle following the guidelines provided in the documentation at this link. To access the styles from my UiBinder xml, I have used ui:with as explained in the documentation available at this guide. While th ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

Expandable sidebar using responsive Twitter Bootstrap

I am in search of a CSS solution to implement a button that can toggle a sidebar on and off using twitter bootstrap. Is there a specific term for those small icons seen on webpages that resemble pull tabs when the sidebar is closed and then move along wit ...

Guidelines for setting up Kendo notifications using an angularjs service

I have successfully defined the Kendo notification in my Angular service. However, when I try to use it with the line uiService.notify.error("You missed some required fields.");, I am getting an error that says "Cannot read property 'show' of nul ...

Ways to heighten the `RadComboBox` `DropDownHeight` featuring `Templates`

One of the challenges I'm facing involves a RadComboBox setup like this: <telerik:RadComboBox ID="RadComboBoxNames" runat="server" Width="470px" DropDownAutoWidth="Enabled" MaxHeight="363px" Skin="MySkin" EmptyMessage="Select" High ...