I'm trying to create an add-on on for gSheets to display a sidebar or dialog with a dynamic number of buttons derived from text in a cell which has been clicked on.
There is a varying number of words in the cells of the target column. The objective is to load the words into a single-dimensional array and use each word as the label of a button. Then by clicking on a button, the same text appearing as the button label is copied to the clipboard.
I've successfully gotten the contents of a selected cell to load into an array as follows (the target strings are delimited by a period):
function splitText() {
var array1 = [{}];
var string1 = SpreadsheetApp.getActiveRange().getValue();
array1 = string1.split('. ');
for(var i=0; i<array1.length; i++){
array1[i] = '\\n'+'\\n'+array1[i];
}
Including custom buttons in a sidebar requires referencing an HTML file which I'm doing as follows:
function openSidebar(){
var html = HtmlService.createHtmlOutputFromFile('Sidebar').setTitle('Text Copy Buttons');
SpreadsheetApp.getUi().showSidebar(html);
}
I'm familiar with the basic HTML to create a button as follows:
<body>
<button onclick='myFunction()' id='button1'>LABEL TO BE ASSIGNED</button>
</body>
I'd like to know how to create a variable number of buttons by looping through the array and assigning each array value to a new button label. Any suggestions much appreciated!
You can try jQuery:
Flow:
Serve basic HTML with buttons inside a div
On Window Load run splitText function on server side with google.script.run
Receive the array from splitText and update div with jQuery append
Alternatively, You can directly use Templated HTML to do a for-loop to append.
Index.html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run.withSuccessHandler(showButtons)
.splitText()
});
function showButtons(arr){
var b = $('#buttons');
b.empty();
for (var i=0;i<arr.length;i++){
b.append("<button onclick='myFunction()' id='button"+i+"'>"+arr[i]+"</button>")
}
}
</script>
</head>
<body>
<div id ="buttons">
<button onclick='myFunction()' id='button'>LABEL TO BE ASSIGNED</button>
</div>
</body>
Code.gs:
function splitText() {
return SpreadsheetApp.getActiveRange().getValue()
.toString()
.split('. ');
}
References:
TemplatedHTML
jQuery vs Template
Related
I have several pages on a website that use the same header for each page. I was wondering if there was some way to simply reference a file with the html for the header sort of like in this pseudo code:
<!-- Main Page -->
<body>
<html_import_element src = "myheadertemplate.html">
<body>
Then in a separate file:
<!-- my header template html -->
<div>
<h1>This is my header</h1>
<div id = "navbar">
<div class = "Tab">Home</div>
<div class = "Tab">Contact</div>
</div>
</div>
This way I could write the header html once and just import it in each of my pages where I need it by writing one simple tag. Is this possible? Can I do this with XML?
You could do it in this fashion below.
<head>
<link rel="import" href="myheadertemplate.html">
</head>
where you could have your myheadertemplate.html
<div>
<h1>This is my header</h1>
<div id = "navbar">
<div class = "Tab">Home</div>
<div class = "Tab">Contact</div>
</div>
</div>
You can then use it with JS below
var content = document.querySelector('link[rel="import"]').import;
So, after a long time I actually found a way to do this using AJAX. HTML Imports are a great solution, but the support across browsers is severely lacking as of 04/2017, so I came up with a better solution. Here's my source code:
function HTMLImporter() {}
HTMLImporter.import = function (url) {
var error, http_request, load, script;
script =
document.currentScript || document.scripts[document.scripts.length - 1];
load = function (event) {
var attribute, index, index1, new_script, old_script, scripts, wrapper;
wrapper = document.createElement("div");
wrapper.innerHTML = this.responseText;
scripts = wrapper.getElementsByTagName("SCRIPT");
for (index = scripts.length - 1; index > -1; --index) {
old_script = scripts[index];
new_script = document.createElement("script");
new_script.innerHTML = old_script.innerHTML;
for (index1 = old_script.attributes.length - 1; index1 > -1; --index1) {
attribute = old_script.attributes[index1];
new_script.setAttribute(attribute.name, attribute.value);
}
old_script.parentNode.replaceChild(new_script, old_script);
}
while (wrapper.firstChild) {
script.parentNode.insertBefore(
wrapper.removeChild(wrapper.firstChild),
script
);
}
script.parentNode.removeChild(script);
this.removeEventListener("error", error);
this.removeEventListener("load", load);
};
error = function (event) {
this.removeEventListener("error", error);
this.removeEventListener("load", load);
alert("there was an error!");
};
http_request = new XMLHttpRequest();
http_request.addEventListener("error", error);
http_request.addEventListener("load", load);
http_request.open("GET", url);
http_request.send();
};
Now when I want to import HTML into another document, all I have to do is add a script tag like this:
<script>HTMLImporter.import("my-template.html");</script>
My function will actually replace the script tag used to call the import with the contents of my-template.html and it will execute any scripts found in the template. No special format is required for the template, just write the HTML you want to appear in your code.
As far as I know it's not possible. You can load the header as a webpage in a iframe element though. In the past webpages were built with frame elements to load seperate parts of a webpage, this is not recommended and support in current browsers is due to legacy.
In most cases this is done with server side languages like php with as example include("header.php");.
I have unordered list of links. Using JQuery, when clicked, the link's contents (a div with image and text) are loaded into the section specified. This all works beautifully. But I'm wondering how to also get the onclick function to move the view to the div's location on the page similarly to how anchor tag works. Here is the site where you can see the div being populated, but not moving down to view it. https://www.thecompassconcerts.com/artists.php
My JQuery knowledge is not awesome (I'm being generous).
I followed Osama's suggestion to add event listener and I got almost correct results. Upon first click...contents are loaded but do not move. But on every successive click, it functions perfectly: Contents loaded and move to div (like an anchor link) works! BUT...not on Safari or Mobile Safari.
Here is my jQuery. I assume if first click is not working that I must add listener before the first click?? Can the event listeners be added on page load BEFORE the function to prevent default click, etc.?
<script>
// BEGIN FUNCTION TO CAPTURE AND INSERT CONTENT
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
</script>
Here is the HTML with links in unordered list
<!-- CONTRIBUTING ARTISTS LIST AND BIOS -->
<section id="artists">
<h2>Contributing Artists</h2>
<ul class="cols">
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
<li><a class="bio" href="performers/first-last.html">First Last</a></li>
</ul>
</section>
Here is HTML of Section where code is being inserted by function
<!-- Performer Bios Dynamically updated -->
<section id="performbio">
</section>
Here is div contents that are being inserted
<div class="artistbio">
<p class="artistname">First Last</p>
<img class="artistimg" src="performers/img/name.jpg">
<p>lots of text here</p>
</div>
If I understand it right, you want to scroll to the section where the details appear on clicking any item in the list but through js and not HTML. In that case, you would add an onclick listener on to the list elements like so:
listElement.onclick = moveToDiv;
The function:
function moveToDiv() {
document.location = "#performbio";
}
A simple way to add a listener to all of the elements:
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
For the edited post, you need to move the function definition out of the document.ready function. you would change the script to:
// FUNCTION TO MOVE TO LOCATION
function moveToDiv() {
document.location = "#performbio";
}
$(document).ready(function () {
// PREVENT DEFAULT LINK ACTION
$('.bio').click(function (e) {
e.preventDefault();
// ADD LISTENER TO EACH ITEM BY CLASS
var list = document.getElementsByClassName("bio");
for (let i = 0; i < list.length; i++) {
list[i].onclick = moveToDiv;
}
// STORE the page contents
var link = $(this).attr("href");
// load the contents into #performbio div
$('#performbio').load(link);
});
});
Another Solution: Using scrollIntoView
First, get all the elements into a variable using querySelectorAll
var elements = document.querySelectorAll(".bio");
Then create a function, for the scrolling part:
function scroll(element) {
element.scrollIntoView();
}
Then just add the onclick listener:
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
scroll(elements[i]);
});
}
I found it very frustrating to try to accomplish these two tasks so instead of a jQuery solution I opted for a CSS solution.
I populated my DIV with all the php includes, gave them unique id's for the anchors to work and then used CSS to hide them by default until clicked and it works like a charm....shows only what I need to show and goes there like an anchor is supposed to.
I must thank Ghost for all of your help and efforts to try and solve this via jQuery. You were very kind and generous.
Here is the code I used:
My collection of links.
<li><a class="bio" href="#artist-name1">Name 1</a></li>
<li><a class="bio" href="#artist-name2">Name 2</a></li>
which anchors to these divs
<div class="bio-container" id="artist-name1">
<?php include('performers/name-lastname.html'); ?>
</div>
<div class="bio-container" id="artist-name2">
<?php include('performers/name-lastname.html'); ?>
</div>
Then I use this CSS to hide those divs until the anchors are clicked.
I'm using [id*="artist-"] to target only links with such text...very easy. Not ideal for a massive list...but mine is not so large so it will do for this situation.
[id*="artist-"] {display: none;}
[id*="artist-"]:target {display: block;}
I'm using a script to do a mouseover effect with images and also highlighting text in a different color using the getElementById phrase. I understand that an ID can only be used once, and if it needs to be used more than once I should use class. But there is no getElementByClass function. I have 2 areas of type that I want to highlight, one is centered, the other is left justified. Is there a way to use the same id for both styles?
<div id="georgia">
<style="text-align: center;">
<strong>Headquarters:
</strong>
</style>more text here
</div>
This is the script I am using:
<script type="text/javascript">// < ![CDATA[
function on(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="green";
};
};
function off(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="";
};
};
// ]]></script>
So what you are saying is I can replace the getElementById with getElementByClassName then it will work?
This is the format I'm using, the first part of the text (Headquarters) is not showing up, but the second part (more text here) is fine.
You need to use document.getElementsByClassName, which returns a list of the objects with that class name:
var all = document.getElementsByClassName("bar");
for(var i = 0; i < all.length; i++){
var obj = all[i];
obj.style.fontWeight = 'bold';
}
<div id="foo" class="bar">hi</div>
<div class="bar">bye</div>
<div id="bar">sup</div>
On Google sites on edit mode, I have prepared a checkbox using Insert - HTML Box
and within the HTML Box the following code..
<style>
div{
width:100px;
height:30px;
}
</style>
<script>
function putResult(e) {
var ss = SpreadsheetApp.openById("0AkkxdNrvyzqzdE1yU21FRGJ6akJ6MmZiSVhTN0JMNnc");
var calc = ss.getSheetByName("Customer");
var chvalue = e.parameter.bike
calc.getRange("C3").setValue("chvalue");
}
</script>
<div>
EDC:
<input type="checkbox" id="bike" onclick="putResult(e)">
</div>
Now my requirements:
I want simply a True/False based on checkbox to be populated in the SS.Calc (C3) Sheet.
The page should automatically be refreshed each time the checkbox is clicked.
I am a novice and in learning stage. Please do shout if things are unclear.
PS:
I copied some code within GAS, that's where the e.parameter.bike comes from, don't know if that's the right way...
I have also inserted a chart in the Google sites with source data from spreadsheet (insert Chart), I want to make it dynamic using checkboxes.
Old but, since April 2018 they implemented a checkbox in spreadsheets.
You can find it in Menu > insert > checkbox or if you add a datavalidation.
Dealing with your Task by simply checking the field value with
=IF(A1=TRUE();"Checked";"Unchecked")
should be way more easy now! It also instantly checks state changes.
I think HTML Box is not accepting onclick , not sure but by inspecting the checkbox in firebug you can see that there is no onclick for the element.
I think you can do it using google app script as follows,
In code.gs file,
function doGet() {
return HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.NATIVE);
}
and have file called Test.html.This can be created File --> New --> Script File, in that have the following code,
<style>
div{
width:100px;
height:30px;
}
</style>
<script>
function putResult() {
var ss = SpreadsheetApp.openById("0AkkxdNrvyzqzdE1yU21FRGJ6akJ6MmZiSVhTN0JMNnc");
var calc = ss.getSheetByName("Customer");
var chvalue = document.getElementById('bike').value;
calc.getRange("C3").setValue("chvalue");
}
</script>
<div>
EDC:
<input type="checkbox" id="bike" onclick="putResult()">
</div>
I haven't tested the above code.Try this if it works for you.
In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.