Replace text with image Google Script? - javascript

I am trying to use this API to run an iteration over some Google Documents. However, I have very little experience concerning Javascript. How would I replace a keyword, say <"image">, with an actual inline image from a URL? Does ChildIndex support indexes within a paragraph? Bonus points for code!

If you want to add an actual inline image from a URL, try this:
var img_name_Url = "URL of the image";
var img_name_Blob = UrlFetchApp.fetch(img_name).getBlob().setName("img_name_Blob");
In the document you want to use it in:
htmlBody : "The content for the inline image <img src='cid:img_name'>",
inlineImages:
{
img: img_name_Blob
}

Related

Javascript that automatically fills in HTML file path for images

I'm trying to use window.location.pathname and injecting innerHTML to generate the file paths for an image so all I need to do is type fileName.png in a div in the html body and have the javascript generate the file path behind it so that it displays the image in the rendered website. This is for images that aren't stored in the same folder as the working file.
I've had mild success but it only works for one image per page which isn't very helpful.
I've gotten this code to work for one image per page:
<div class="picName">pic.png</div><div id=<"shortcut"></div>`
<script>
var relativePath = window.location.pathname;
var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
document.getElementById("matts-shortcut").innerHTML =
'<src=\'/images' + relativePath + '/' + picName + '\'>';
</script>
The solution below pulls images names from with Divs using .querySelectorAll() which returns a DOM NodeList. The NodeList is useful because it has a forEach() method that can be used to loop over each item is the list. Loop over each list item using it's textContent property as the image name. Then you'll need to create a new image element for each image. To do that you can do something similar to this.
let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
let picName = image.textContent;
// Create a new image element
let imgEl = document.createElement('img');
// Set the src attribute of the image element to the constructed URL
// the name of the picture will be the div text content
// This is done with a template literal that you can learn about here:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
imgEl.src = `${relativePath}/${image.textContent}`;
// Now we have a real image element, but we need to place it into the DOM so it shows up
// Clear the image name
image.textContent = "";
// Place the image in the Div
image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>
EDIT: In response to Ismael's criticism, I've edited the code slightly and commented every line so you can learn from this answer. There are two hyperlinks referenced in the code to help you think about coding in a modern way and so you can interpret modern code you read more easily.
About:
Arrow functions
Template Literals
Edit 2:
With further clarification, the answer has been amended to pull the image file names from Div elements already in the DOM.
Let ID equal your element's id
Call on:
document.getElementById(ID).src = "image_src"
When you want to change images, like an onclick action or as part of a function.

Replace Label/span with an already made Label/span

I'm trying to replace the words in a span ("Grades")
<span class="vui-heading-1">Grades</span>
with a more definite name from another label (the title="Peer Tutor Training")
<a class="d2l-menuflyout-link-link" title="Peer Tutor Training" href="/d2l/home/419542">Peer Tutor Training</a>
Wanting the title to replace when the page loads, as I'm using this to replace a span wording in an iframe with the title within the same iframe.
Not entirely sure how to go about this. Thanks in advance!
NOTE Upon further inspection, it turns out that the from the original page is not actually included into the iframe. Workaround method I'm requesting help with is an onload function to replace the "Grades" text in to "Peer Tutoring Training" (or other text since this is only one example)
var $iframe = $('iframe#your-iframe'); // iframe that u wanna modify
$iframe.on('load',function(e) {
// get the title value
var title = $(this).find('a.d2l-menuflyout-link-link').attr('title');
// get the span element
var $span = $(this).find('span.vui-heading-1');
// replace the text in the span
$span.text(title);
});

Squarespace - How to display description/custom text on index thumbnail on hover

Basically, I want to be able to show title and some text on hover on all my index thumbnail like this website.
http://www.timboelaars.nl/
However, in the current squarespace template that I am using (I believe it's called York), the markup is only grabbing the page title and therefore displaying the page title on hover. (See the below code block, you can see the page title in there, that's the only thing that the template displays on Hover)
<div class="index-item-text-wrapper">
<h2 class="index-item-title">
<a class="index-item-title-link" href="/google-shopping/" data-ajax-loader="ajax-loader-binded"><span class="index-item-title-text">**PAGE TITLE**</span></a>
</h2>
</div>
There's no field for me to put any HTML so I am seeking help to use javascript to manually inject custom HTML markup to every single thumbnail, then show them on hover.
TL;DR I want to be able to display more than just the title on hover (ideally my own HTML markup so I can customize the style) on my thumbnails but that's not supported by the template.
Here is my website http://shensamuel.com/
I am really weak at Javascript and I've searched for a solution for this problem for quite long. Any help will be much appreciated!
Thanks!
The following Javascript can be used to insert text for each tile on the page. The code would be inserted using the footer code injection area (unless you're using Developer Mode in which case you'd insert it with the rest of your scripts).
<script>
(function() {
var tiles = document.getElementsByClassName('index-section');
var thisTile;
var titleText;
var description;
var parent;
var i, I;
for (i=0, I=tiles.length; i<I; i++) {
thisTile = tiles[i];
titleText = thisTile.getElementsByClassName('index-item-title-text')[0];
parent = thisTile.getElementsByClassName('index-item-text-wrapper')[0];
description = document.createElement('span');
description.className = 'index-item-description-text';
switch(titleText.innerHTML.toLowerCase()) {
case "google shopping":
description.innerHTML = "Some custom text.";
break;
case "hana":
description.innerHTML = "More text that's custom.";
break;
case "wali":
description.innerHTML = "Custom text here.";
break;
case "cypress":
description.innerHTML = "Type anything you want.";
break;
case "ryde":
description.innerHTML = "Just another bit of text.";
break;
default:
description.innerHTML = "";
}
parent.appendChild(description);
}
})();
</script>
Observe the pattern in the code in order to add new tiles or edit existing ones. You will see that the script attempts to match (a lower case version of) the 'title' text and then inserts text based on each title. This allows you to add more in the future by repeating this 'case' pattern. Of course if you ever change the title of a tile you'd have to correspondingly change this Javascript code.
You can then style the description by inserting CSS via the Squarespace CSS Editor (or via your base.less file if using Developer Mode). For example:
.index-item-description-text {
display: block;
font-size: 1.2em;
color: #FFFFFF
}
Note that while there is an alternative method that would use each tile's respective URL to do an AJAX query and obtain meta data about each project (and therefore allow you to use the Squarespace content manager to insert this 'description'), that method seems unnecessarily complex for your case.
Update 8/17/2016: Regarding AJAX and how to disable AJAX loader in Squarespace: Jason Barone has suggested adding this snippet to your Code Injection > Footer to disable the "AJAX" pageloader. He noted that it will disable the smooth, AJAX transitions between pages, but will allow custom Javascript like usual.
<script>
//Credit: Jason Barone, http://jasonbarone.com/
window.Template.Constants.AJAXLOADER = false;
</script>
Also, some templates have an option to disable AJAX within the style editor (image credit: SSSUPERS):
Update 9/28/2016:
It has been reported that the code provided above no longer disable AJAX. However, some newer templates have added an 'Enable AJAX Loading' setting that can be toggled off.

get snippet of html text without creating a DOM?

Given a html, I'd like to get first 100 characters of text (content without the markups)
I could create a jquery object with the html and use .text().
But the problem is that browsers may load all the images in the html.
So I wonder if there's a way to extract text snippet from html without building a DOM.
edit
given a html (just a string of html, not part of DOM yet)
<p>my lord</p><img src="some_url"><br>I'm overloaded
I could do $('<div/>').append(html).text().substr(0, 5); to get 5 characters.
But the img is downloaded by browser, and I don't want that.
var s = "<p>my lord</p><img src=\"some_url\"><br>I'm overloaded"
s = s.replace(/<[^>]+>/g,'').substr(0, 100);
You could remove the image elements and then load it to the dom
Something like
var html = "<p>my lord</p><img src="some_url"><br>I'm overloaded";
html = html.replace(/<img[^>]*>/g,"");
var firstFive = $('<div/>').append(html).text().substr(0, 5);

How can my userscript select this link based on the contained image src?

I'd like to write a userscript automate a click on a certain image on a web page.
The target URL is dynamic, but the image name is fixed.
So far I have the following Userscript
//--- Note that the contains() text is case-sensitive.
var TargetLink = $("a:contains('Click link.jpg')")
if (TargetLink && TargetLink.length)
window.location.href = TargetLink[0].href
Following is an extract of the web page, which I need a user script
<a target="_blank" href="http://www.movshare.net/video/0zq2u9732nvdf"><img border="0" src="http://img.movie2k.to/img/click_link.jpg" alt="view Rise of the Guardians" title="view Rise of the Guardians" width="742"></a>
PS: alt and title of the image attributes are dynamic. Img SCR is fixed.
:contains() searches for text; it will not match against the image source.
The image source does not contain Click link.jpg. It contains click_link.jpg. The underscore and correct case are critical.
Given that, this code will select the right link:
var TargetLink = $("a:has(img[src*='click_link.jpg'])");

Categories

Resources