Javascript (onclick) pop up bigger image window from image array - javascript

I have an array of images that populate the page and what I am having trouble with is coming up with a way to create an ONCLICK popup image window from the thumbnails (but the popup window needs to be a bigger size image):
here is the js code:
var str = "<table>";
var imgFolder = "images/";
var cover = new Array();
cover[0] = "kitchenHouseSale.jpg";
cover[1] = "eatLive.jpg";
cover[2] = "loveAnthonySale.jpg";
var coverone = new Array();
coverone[0] = "casualVacancy.jpg";
coverone[1] = "quiet.jpg";
coverone[2] = "whirlAway.jpg";
var covertwo = new Array();
covertwo[0] = "everyLastSale.jpg";
covertwo[1] = "neilYoung.jpg";
covertwo[2] = "soupSisters.jpg";
var title = new Array();
title[0] = "The Kitchen House";
title[1] = "Eat to Live";
title[2] = "Love Anthony";
for (var i = 0; i < cover.length; i++)
{
str += "<tr><td colspan='2'><h2>" + category[i] + "</h2></td></tr>";
str += "<tr><td class='basket'><img src='" + imgFolder + cover[i] + "' width='108' height='159'>
}
str += "</table>";
var elem = document.getElementById("table");
elem.innerHTML = str;
Any help is appreciated. Thanks!

Do i get you right? You want the user to click on an image and a bigger version of the same image is supposed to appear in a popup-window?
Have a look at window.open() then: http://w3schools.com/jsref/met_win_open.asp
You must specify the absolute path of the image - file as the url for the popup, like http://your.domain.com/images/kitchenHouseSale.jpg.
you can then add an onclick-handler to the img-tag, something like this:
<img src='" + imgFolder + cover[i] + "' width='108' height='159' onclick="window.open('http://your.domain.com + this.src)" />

Related

Converting emails to PDF if subject equals "xxxxx" and date equals today

I have written a script which has a trigger to run every hour, it searches my emails and extracts the data, turns it to a PDF and locates it in a folder if the subject equals "xxxx", it overwrites data in the folder if it already exists.. I would like to add in a new if function where it will only pick up emails for the current day and not history (to save efficiency of the script and data)
function saveGmailAsPDF2() {
var gmailLabels = 'xxxxx';
var driveFolder = DriveApp.getFolderById("folder url");
var threads = GmailApp.search("subject:" + gmailLabels,0,20);
if (threads.length > 0) {
/* Google Drive folder where the Files would be saved */
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
/* Gmail Label that contains the queue */
var label = GmailApp.getUserLabelByName(gmailLabels) ?
GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
for (var t=0; t<threads.length; t++) {
threads[t].removeLabel(label);
var msgs = threads[t].getMessages();
var html = "";
var subject = threads[t].getFirstMessageSubject();
var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
if (previousdoc.hasNext()) {
previousdoc.next().setTrashed(true);}
/* Append all the threads in a message in an HTML document */
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
html += "From: " + msg.getFrom() + "<br />";
html += "To: " + msg.getTo() + "<br />";
html += "Date: " + msg.getDate() + "<br />";
html += "Subject: " + msg.getSubject() + "<br />";
html += "<hr />";
html += msg.getBody().replace(/<img[^>]*>/g,"");
html += "<hr />";}
/* Convert the Email Thread into a PDF File */
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
tempFile.setTrashed(true);}}}
Explanation:
There is a function getLastMessageDate() that gives the date of a thread's most recent message. You can compare that against the date of today and if they match execute the rest of the code.
Since you use a for loop: for (var t=0; t<threads.length; t++)
I think the condition if (threads.length > 0) is redundant because for loop won't run anyway if threads.length equals 0.
Because of the latter, I transferred the folder creation part of your code into the loop itself and execute it only when the last day of the thread is equal to today. But I leave this part for you to decide.
I can't test your code but this should work:
function saveGmailAsPDF2() {
var gmailLabels = 'xxxxx';
var driveFolder = DriveApp.getFolderById("folder url");
var threads = GmailApp.search("subject:" + gmailLabels,0,20);
// new code
const today = new Date();
const ss = SpreadsheetApp.getActive();
const timezone = ss.getSpreadsheetTimeZone();
const today_dt = Utilities.formatDate(today, timezone, 'yyyy-MM-dd');
///////////
for (var t=0; t<threads.length; t++) {
// new code
var lastMessageDate = threads[t].getLastMessageDate();
var thread_dt = Utilities.formatDate(lastMessageDate, timezone, 'yyyy-MM-dd');
if(today_dt==thread_dt){
///////////
/* Google Drive folder where the Files would be saved */
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
/* Gmail Label that contains the queue */
var label = GmailApp.getUserLabelByName(gmailLabels) ?
GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
threads[t].removeLabel(label);
var msgs = threads[t].getMessages();
var html = "";
var subject = threads[t].getFirstMessageSubject();
var previousdoc = driveFolder.getFilesByName(subject + ".pdf"); //gets name of csv, if exists in drive then move to trash before creating new file
if (previousdoc.hasNext()) {
previousdoc.next().setTrashed(true);}
/* Append all the threads in a message in an HTML document */
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
html += "From: " + msg.getFrom() + "<br />";
html += "To: " + msg.getTo() + "<br />";
html += "Date: " + msg.getDate() + "<br />";
html += "Subject: " + msg.getSubject() + "<br />";
html += "<hr />";
html += msg.getBody().replace(/<img[^>]*>/g,"");
html += "<hr />";}
/* Convert the Email Thread into a PDF File */
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
tempFile.setTrashed(true);}}}

How can I make sure each dynamically created image is taking on its own information/data pulled from the API?

Is there a way for me to make sure each img tag created also contains or can be linked with its individual data from the api? If only one image is returned in the search, it will give me the data for that image. However, if multiple images are returned, once clicked, it will return a only one possible image and data. I am new to coding and javascript in general, so please forgive any rookie mistakes. Thanks!
var scryfallURL = "https://api.scryfall.com/cards/search?q=";
var cardName = "";
var container = $("#list");
$("#searchBtn").on("click", function(event) {
event.preventDefault();
container.empty();
cardName = $("#search").val().trim();
queryURL = scryfallURL + cardName;
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
debugger;
var result = response.data;
console.log(result);
$('#search').val('');
//loops through creating an image tag for each search result
for (let index = 0; index < result.length; index++) {
var showCard = $("#list").append("<image src=' " + result[index].image_uris["normal"] + "' ></image>", "</br>");
var name = result[index].name + "<br>";
var creature = result[index].type_line + "<br>";
var flavorText = result[index].flavor_text + "<br>";
var legality = result[index].legalities + "<br>";
var cardFront = "<image src=' " + result[index].image_uris["large"] + "' ></image>" + "<br>";
};
// click function to clear the div and replace with only one card image and info
showCard.click(function() {
$("#searchForm").empty();
container.empty();
$("#info").append(name, creature, flavorText, legality);
$("#oneCard").append(cardFront);
})
});
});

Dynamic Color-Thief / Get dominant color

I have a very special problem with color-thief. I'm trying to load some data from my datatable containing a realtive path to a image stored on the same domain.
There are about 20 links where I have to grab the dominant color and push it to an array.
My problem is now, that when i load my data (with AJAX) and I try to grab the color, the image is not loaded jet and i get a "Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0."
So here is what i have tried so far:
METHODE 1: GetColor
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.src = result[i + 2];
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 2: GetColorByUrl
// Create Objects for colorThief
var colorThief = new ColorThief();
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
//Also tried with a absolute path, not changing anything
var color = colorThief.getColorFromUrl(result[i + 2]);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
METHODE 3: Append Image to HTML
var colorThief = new ColorThief();
var colors = [];
var content = "<div id='temp' style='display:none'>";
//Create options
for (var i = 0; i < result.length; i += 3) {
options += "<option value='" + result[i] + "'>" + result[i + 1] + "</option>";
content += "<img src='" + result[i + 2] + "'>";
}
content += "</div>"
$("#contentRightTop").append(content);
var thisColor;
var theseColors = [];
$("#temp img").each(function () {
thisColor = colorThief.getColor(this);
theseColors.push(thisColor);
});
$("#temp").remove();
METHODE 4: Object.onload
// Create Objects for colorThief
var colorThief = new ColorThief();
var myImage = new Image;
var colors = [];
for (var i = 0; i < result.length; i += 3) {
labels.push(result[i]);
data.push(result[i + 1]);
myImage.onload = function() {
var color = colorThief.getColor(myImage);
colors.push("#" + rgbToHex(color[0]) + rgbToHex(color[1]) + rgbToHex(color[2]));
}
myImage.src = result[i + 2];
}
So how i told you, so far nothing really worked. I also tried to set absolute paths to my domain.
THE ONLY methode that worked, was a try catch, with repeating the whole for loop, what wasn't that nice.
So guys if you would have some ideas/inputs on how to solve this problem or also alternatives to color-thied (it's very heavy) would be great.
Mention, that i allready tried to combine/replace color-thief with this scipts:
ImagesLoaded - Very bugy in Google Chrome
Colorify - Didn't manage to change the script to what i need
[Dominant-Color - Has imagemagick dependencie, that i want to avoid]
[Adaptive Background - Same as Colorify]
[PrimaryColor - I have to give it a try again, think there was an error in my code]
(Only allowed to post 2 links^^)
Thanks so far
Martin

AppendChild Javascript

I am trying to append images to a bootstrap column but having no luck, does anyone know what is wrong with my code.
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Any help is appreciated.
Thanks
Sorry, but your code doesn't really make any sense. There are lots of things wrong with it:
Here's what you started with:
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Issues:
You create an <img> DOM object, but don't do anything with it.
You need to pass a DOM object to appendChild() NOT pass a string.
You can't construct a string of HTML by adding img[0] into the string. It simply doesn't work that way at all. You either work entirely in HTML strings or you work in constructed HTML objects or you create an HTML object and then set .innerHTML to a string of HTML. You can't just mix the two the way you are.
I'll take a guess at what you want to do:
for (i = 0; i <= 11; i++) {
var src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
var row = document.createElement("div");
row.className = 'row';
row.innerHTML = "<div class='col-md-2'><img src='" + src + "'></div>";
document.body.appendChild(row);
}
This code take the following steps:
Calculate the image src URL.
Create your container div DOM object.
Set the desired className on the container object.
Set the .innerHTML property of the container to the HTML string for the HTML that you want in the container (this will automatically create that set of DOM objects in the container).
Append the container to your document.
Here is an all-javascript solution
var camera = ['http://placehold.it/200x200']
for (i = 0; i <= 0; i++) {
var img = new Image();
img.src = camera[i];
var row = document.createElement('div');
row.className = 'row';
var imgContainer = document.createElement('div');
imgContainer.className = 'col-md-2';
imgContainer.appendChild(img);
row.appendChild(imgContainer);
document.body.appendChild(row);
}
and a jsfiddle demo http://jsfiddle.net/576Tm/1

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

Categories