Image Gallery hosted in Google Drive Folder - javascript

I've been looking for a way to create a gallery on a website with images from a folder in my google drive. Which I have shared here: https://drive.google.com/drive/u/0/folders/0Bwx-OwnNeIvwRldSVlU5SGN0dGs
inside it is a simple HTML, and a gallery folder with pictures of monster trucks and cute animals. And the goal is here to create a gallery where people can upload images of well; monster trucks and cute animals.
I've been searching for all kinds of methods of achieving this and this is what I have found so far:
In short what I am trying to achieve is to get the id's of images in a publicly shared folder in my G-Drive. Then use those id's to create a gallery via JS in an HTML.
What my HTML looks like now:
index.html
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<!-- all divs will append here -->
</div>
What I researched on the Drive SDK:
I've been using the "try it" section here to figure out what i need to do. https://developers.google.com/drive/v2/reference/children/list#examples
Request result: GET https://www.googleapis.com/drive/v2/files/0Bwx-OwnNeIvwRG5rNzZ6OURSNEk/children?fields=items%2Fid
Response result:
200 OK
- SHOW HEADERS -
{
"items": [
{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
},
{
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
},
{
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
},
{
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
},
{
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
},
{
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]}
What I would like for the script to do:
script.js
var imageIds = <!-- ids from the the response --> ;
var x = imageIds.length;
for (var i = 0; i < x; i++) {
<!-- create a <div> -->
}
//See below*
Create a div: In the for loop it will create a <div> with a specific "class" and an <img> inside that div, with a "src="http://drive.google.com/uc?export=view&id=IMAGE-ID" where the "IMAGE-ID" was gotten from the "Response". the <div> will then be appended to <div id="gallery"> in the index.html.
What I would like for the end HTML do look like:
index.html:
<h1>Cute Animals & <br>
Monster Vehicles</h1>
<div id="gallery">
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwaFZXVzVmMl9ILUU">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwVk1DTEpnR0J6VHc">
</div>
<div class="brick">
<img src="http://drive.google.com/uc?export=view&id=0Bwx-OwnNeIvwblBHLVEza0hxY2s">
</div>
<!-- and so on ... -->
</div>
What I am unsure of now, is how this needs to be authenticated to get the image-ids from the G-Drive folder. This could be hosted from Google Drive itself with their hosting links, or it could be created through Google Apps Script, and the functionality to serve HTML there, and that would make the authentication easier as you can get everything from drive directly.
I don't understand why this is no where to be found, that does not involve a payment. It would be great if everyone had the opportunity to create image galleries from images in a G-Drive folder.
Would really like your help on this one. Thanks alot.

Firstly, about the code itself, it would be something like that:
document.addEventListener('DOMContentLoaded', function() {
var response = {
"items": [{
"id": "0Bwx-OwnNeIvwaFZXVzVmMl9ILUU"
}, {
"id": "0Bwx-OwnNeIvwVk1DTEpnR0J6VHc"
}, {
"id": "0Bwx-OwnNeIvwblBHLVEza0hxY2s"
}, {
"id": "0Bwx-OwnNeIvwTkZZVXp0dDg4bXc"
}, {
"id": "0Bwx-OwnNeIvwZTN1YzZrcm53eFE"
}, {
"id": "0Bwx-OwnNeIvwYkZ5ZXpjWHhKcFk"
}]
};
var imageIds = response.items.map(function(item) {
return '<div class="brick"><img src="http://drive.google.com/uc?export=view&id=' + item.id + '"></div>';
});
document.getElementById('gallery').insertAdjacentHTML('afterbegin', imageIds.join(''));
});
<div id="gallery"></div>
About the authorization, take a look at their documentation.

Related

How to replace JS variable with JSON file

I've been working on a website and am new to the website coding scene, my goal is to create a revolving text that goes between words sort of like a splash text on games like Minecraft. I know it's probably best to somehow create a way to connect to a JSON file to my JS one but not quite sure on how to do it. Can someone help?
This is my JS so far and the part of my site that shows the revolving text.
var landingswitchtext = [
'world',
'web',
'video',
'community',
'service',
'home',
'place',
'legacy',
'space',
'server'
];
textSequence(0);
function textSequence(i) {
if (landingswitchtext.length > i) {
setTimeout(function() {
document.getElementById("landing-text-switch").innerHTML = landingswitchtext[i];
textSequence(++i);
}, 2500); // 2.5s (in milliseconds)
} else if (landingswitchtext.length == i) { // Loop
textSequence(0);
}
}
<div class="landing-page">
<h1 class="landing-text">
<center>
building a
<br>
<br>
<span class="magic" id="landing-text-switch">sam</span>
<br>
<br>
for everyone.
</center>
</h1>
</div>
So, you need to have a JSON file and then import it in your script. For that, try the following script:
import * as data from './example.json';
And then use the variable data anywhere you want.

Display Images from JSON Array using JavaScript

I tried to display an image from the image folder in JSON array to Javascript but I am not sure if I am getting the right path.
When the click event happens, everything works except for the image is not showing in the <img id "picture">, the picture is not showing up in the img section of my HTML.
I tried to change the path to ../Images/room_1.jpg but it still not working.
FYI: I have a separate folder that stores images, both json and js are stored in the javascript folder. should I put the same image file in the javascript folder?
html
<h2>Select a Hotel</h2>
<ul class ="hotels">
<li> Marriott Hotel Rooms</li>
</ul>
<h2 id="hotelName">Hotel</h2>
<h3>Adress: <span id="address"></span></h3>
<img id="picture">
Hotel.json
{
"hotels": [
{
"name": "Marriott",
"address": "098 hollywood Street",
"picture": "room_1.jpg"
}
JS
async function getHotelData() {
try {
const response = await fetch('Javascript//hotel.json')
return await response.json()
} catch (error) {
console.error(error)
}
}
let hotelData = {}
getHotelData().then(data => hotelData = data)
const hotelEvent = document.querySelectorAll("a").forEach(a => {
a.addEventListener('click', hotelInfo )
})
function hotelInfo(event) {
let hotelChoice = hotelData.hotels.find(hotel => {
return event.target.id === hotel.name.toLowerCase()
return event.target.id === hotel.address.toLowerCase()
return event.target.id === hotel.picture.toLowerCase()
})
console.log(hotelChoice)
document.querySelector("#hotelName").textContent = `${hotelChoice.name} Hotel`
document.querySelector("#address").textContent = `${hotelChoice.address}`
document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`
}
You need to set the src property to the image instead of setting its innerHTML.
A normal img tag would look something like this:
<img id="image" src="/path/to/image.png">
You need to replicate the same using JavaScript:
document.querySelector("#picture").innerHTML = `${hotelChoice.picture}`
// Becomes
document.querySelector("#picture").src = `${hotelChoice.picture}`
Also, pay attention to the image path inside the JSON file, it should be relative to the HTML document you're using it, not the JavaScript one. So if your images are stored inside a separate directory you should change the path inside your JSON file accordingly.
Example:
If your HTML file is in the project root and there is an images folder, you JSON should be something like:
{
"hotels": [
{
"name": "Something",
"address": "Some Street, 12",
"picture": "images/picture_name.jpg"
}
]
}

Use AJAX to load content to a jQuery UI dialog

On my site, I have a bunch of profile previews that are being generated by running JSON data through a mustache.js template.
Here's the template:
<script id="profile-preview-template" type="text/template">
<div class="col-sm-3">
<a style="display:block">
<div class="profile-preview">
<img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
<h1>{{first_name}} {{last_name}}</h1>
<h2 class="text-muted">{{major}}</h2>
<h3 class="text-muted">Cohort {{cohort}}</h3>
</div>
</a>
</div>
</script>
The profile preview shows select info from the JSON info like first_name, last_name, etc.
Here's the format of the JSON data:
{
"profiles": [
{
"first_name": "Robert",
"last_name": "Hosking",
"img_url": "img/about/hackbert.jpg",
"major": "Computer Science",
"cohort": 12,
"bio": "some info",
"linkedin": "some url",
"home_town": "some place",
"status": "Student"
},
{
"first_name": "Jimmy",
"last_name": "Harval",
"img_url": "img/about/hackbert.jpg",
"major": "Chemistry",
"cohort": 13,
"bio": "some info",
"linkedin": "some url",
"home_town": "some place",
"status": "Student"
}
]
}
However, when one of the previews is clicked, I'd like to make a jQuery UI dialog modal popup containing all of the info in the JSON data (not just the data displayed in the preview).
My question is how do I get a reference as to which profile preview was clicked so I know where in the JSON file to look to get the rest of the information.
I made some slight changes to your HTML and template script.
<div class="profile-full"></div>
<div class="preview"></div>
<script id="profile-preview-template" type="text/template">
<div class="col-sm-3">
<a style="display:block">
<div class="profile-preview">
{{#profiles}}
<img class="img-responsive img-circle center-block" width="200px" src="{{img_url}}" alt="Photo of {{first_name}} {{last_name}}" />
<h1 id="whichProfile">{{first_name}} {{last_name}}</h1>
<h2 class="text-muted">{{major}}</h2>
<h3 class="text-muted">Cohort {{cohort}}</h3>
{{/profiles}}
</div>
</a>
</div>
</script>
As you can see, 2 divs for demonstration purposes.
.profile-full Where the contents of the correct object is output using JSON stringify. What gets output can of course be changed, this is just to show that the correct object is selected.
.preview Where the preview profiles are generated.
I also added the opening and closing {{#profiles}} {{/profiles}}
profile is derived from what is set in the beginning of your json.
"profiles": [
We assume that you have correctly linked the jQuery and mustache.js libraries. Name your json file from your post as data.json
You must also link the .js file below. I have named it main.js.
$(function() {
$.getJSON('data.json', function(data) {
var template = $('#profile-preview-template').html();
var html = Mustache.to_html(template, data);
$('.preview').html(html);
allProfiles = data.profiles;
lookup = [];
for(i=0;i<data.profiles.length;i++) {
lookup.push(data.profiles[i].last_name);
};
});//getJSON
$(document).on('click', '#whichProfile', function() {
var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
var i = jQuery.inArray(whichName, lookup);
$('.profile-full').html(JSON.stringify(allProfiles[i]));
});
});//document ready
So what's happening here?
$(function() {
$.getJSON('data.json', function(data) {
var template = $('#profile-preview-template').html();
var html = Mustache.to_html(template, data);
$('.preview').html(html);
After our document.ready shorthand, we GET the contents of the data.json, and hold it in data. Then we put the contents of html into the div with a class of preview, as we have formatted it according to the template script.
allProfiles = data.profiles;
lookup = [];
for(i=0;i<data.profiles.length;i++) {
lookup.push(data.profiles[i].last_name);
};
});//getJSON
Next we'll create an array called lookup which contains only the last_name data from our json. This will make it possible and fast to get the reference as to which profile preview was clicked.
If you only have a few names, using the last name is fine, but use a unique identifier if the amount of profiles grows (So overlapping last names doesn't occur). Consider adding a unique id, or email to your json.data.
Then close your getJSON.
$(document).on('click', '#whichProfile', function() {
var whichName = $(this).text().substr($(this).text().indexOf(" ") + 1);
var i = jQuery.inArray(whichName, lookup);
$('.profile-full').html(JSON.stringify(allProfiles[i]));
});
});//document ready
Here on clicking a name will get the .text of what's on our page. We will convert it so it's only the last name (strip everything before the space).
We then search for this last name within the lookup array and return its index. Now that we have this index we can use it to get any value within the json relative to the index. In this example we just put the entire stringified contents of the relevant object into our profile-full div
Finally we close our document.ready.
Try clicking on a name (Can be the first or last name). We could of course put anything from that relevant object anywhere else. For example:
remove the line
$('.profile-full').html(JSON.stringify(allProfiles[i]));
and replace it with
alert(allProfiles[i].first_name + ' ' + allProfiles[i].last_name +
' is studying ' + allProfiles[i].major + ' as their Major');
Now clicking on a name will get a pop up, stating their full name and which Major they are studying.
In your template, give each <a> element an id attribute equal to the index of the corresponding profile in the JSON array.
Then, you can give the <a> element an onclick method such as foo(this), because this will pass the element to the function. In your function, you can retrieve the id with $(elem).attr("id"), where elem is the function parameter. Now you have the index of the profile, so it should be easy to retrieve the profile's information.

Inserting Anchors in a Javascript Photo Gallery - Not Working?

I am using jAlbum(with the lightflow skin) to create a photo gallery for my website. The gallery loads and is in a nice carousel format. I would like to add anchors that way I can link directly to a certain photo within the gallery. I tried to add an anchor in the HTML yet it does not work. I assume this is because when the page loads the gallery takes a few seconds to load and thus does not redirect to the anchor. I easily could be wrong and need some advice on what I should try to get anchors to work. Here is an example code for the anchor and the photo itself:
<div class="item">
<a name="anchor3" id="anchor3"></a>
<img class="content hidden" src="thumbs/tree-w-sun.jpg" alt="Gifts" />
<div class="ref hidden">item8</div>
<div class="caption"><h3>Gifts</h3></div>
<div class="comment hidden"></div>
<div class="author hidden"></div>
<div class="params hidden"></div>
<div class="info hidden"><div><p>Artist: UBhapE2</p></div></div>
<div class="thumbWidth hidden">261</div>
<div class="thumbHeight hidden">350</div>
<a id="item8" class="lightwindow hidden" title="<h3>Gifts</h3>"
rel="gal[cat]" href="slides/tree-w-sun.jpg" ></a>
</div>
I have tried linking to the anchor I inserted (anchor3) and to the id inserted by jAlbum (item8) and neither work.
There are a few scripts that control the gallery and will put them here:
Script 1 - "Lightflow JS"
var LightFlowGlobal = {};
function getParam( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Script 2 - "ContentFlow JS" This JS is long and for sake of space I put the link directly to the JS file here
Script 3 - This script is in the page:
<script language="JavaScript" type="text/javascript">
var startItem = getParam('p');
if(startItem == "") startItem = "first";
if(startItem.isNaN) startItem = "'"+startItem+"'";
new ContentFlow('contentFlow', {
reflectionColor: "#000000",
maxItemHeight: 350,
marginTop: 50,
reflectionHeight: 0.25,
endOpacity: 1,
startItem: startItem,
circularFlow: false,
stretchThumbs: false
});
function lightWindowInit() {
LightFlowGlobal.myLightWindow = new lightwindow({
infoTabName : "More Info",
rootPath: "res/lightwindow/",
loadingTxt: "loading or ",
cancelTxt: "cancel",
playTxt: "start slideshow",
stopTxt: "stop slideshow",
slowerTxt: "slower by 1 second",
fasterTxt: "faster by 1 second",
downloadSlideTxt: "Download",
downloadSlide: false,
showSlideshow: false,
slideshowDuration: 5000,
circular: false,
animationDuration: 0.25
});
}
LightFlowGlobal.readyJS=true;
var rootPath = ".";
</script>
I am unsure what other scripts or css is needed. I link to the test-gallery I am working with here if you need to view the page. I will post additional info if requested.
So now how do I get anchors to work with this? I am not that great at javascript so please explain the answer vs "you need to add this function to the script" without explaining.
Thank Your for any and all assistance!
On the ContentFlow site, under Documentation --> items as links, the developer specifically states that "no element within the item may contain any anchors". maybe someone can offer a way around this restriction.
I figured out a way answer was provided by the Photo Gallery Creater:
It's not only the js. You'd need to pass a parameter to AddThis in order to
identify the image. Without it, you wouldn't know which image has been clicked.
The best would be to use LightFlow's query paramter p=index, where index is the
number of the image of the current web page.
For example, the following link would focus the 4th image of the gallery
(index begins at 0): http://your-domain.com/album/index.html?p=3

How to translate into other languages my web page?

How can I translate my web pages? Actually what technology or what scripting-if require- should be used? For info; I have all translated text. But I do not want to create something like clone site for other language.
I used just javascript -including jquery .
Just using JavaScript...
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
</script>
<!-- English Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','en_US');</script></h1>
<p class="content"><script>get_i18n('content','en_US');</script></p>
</div>
<!-- French Version -->
<div class="story">
<h1 class="title"><script>get_i18n('title','fr_FR');</script></h1>
<p class="content"><script>get_i18n('content','fr_FR');</script></p>
</div>
Please Note: This isn't a very graceful solution. I'm sure there's a prettier method...
You actually mean "how to build multi lingual website" as you already have the "translated text" as you call it.
One way is to put the text inside containers then using client side code change the containers contents to the proper text according to selected language, having arrays with translated text in each language.
If you have server side language at your disposal it would be much better though - do you have such thing?
Using CSS attribute selectors:
<style type="text/css">
// hides all French blocks by default
div.story[lang="fr"] {
display: none;
}
// hide all English blocks
body[lang="fr"] div.story[lang="en"] {
display: none;
}
// show all French blocks
body[lang="fr"] div.story[lang="fr"] {
display: block;
}
</style>
<!-- Change this to the language of the blocks you want to display -->
<body lang="fr">
<!-- English block, shown by default -->
<div class="story" lang="en">
<h1 class="title">Article Title</h1>
<p class="content">Content of the Article.</p>
</div>
<!-- French block, hidden by default -->
<div class="story" lang="fr">
<h1 class="title">Titre de l'Article</h1>
<p class="content">Contenu de l'Article.</p>
</div>
</body>
This setup defaults to showing all English blocks, unless lang="fr" is set on the <body> tag.
Of course, you'll still need some way to modify the lang attribute of the <body> tag...
It would take too long for JavaScript to translate your site. I'd say find some software that can translate HTML files and keep both versions on your server. I know this isn't what you want, but it's the only practical way right now.
You can use Cloud Translation, it's a free and open-source project from Angry Monkey Cloud: https://github.com/angrymonkeycloud/CloudTranslation.
You should add a reference to jQuery first, then to the CloudTranslation JavaScript file:
<script crossorigin="anonymous" src="https://cdn.amcapi.com/translation/cloudtranslation-1.0.0.min.js"></script>
And add the configuration within the HTML head as follows:
<script type="application/json" id="CloudTranslationConfig">
{
"Settings": {
"DefaultLanguage": "en",
"TranslatorProvider": "Azure", // not required if you filled in all translations
"TranslatorProviderKey": "{Your Microsoft Azure Translator Key}", // not required if above is empty
"UrlLanguageLocation": "Subdirectory"
},
"Languages": [
{
"Code": "en",
"DisplayName": "English"
},
{
"Code": "ar",
"DisplayName": "Arabic",
"Direction": "rtl"
}
],
"Translations": [
{
"en": "Home",
"ar": "الصفحة الرئيسية"
},
}
</script>
and add your own custom select (dropdown) having the class "CloudTranslationSelect" (you can customize the style of your select the way you want).
More information found on https://www.angrymonkeycloud.com/translation
I have improved the first answer a bit. Just use a function to set the lanaguage value in localStorage and then get the language from there and dynamically change the HTML with the global variable lgn.
<script type="text/javascript">
// JSON-formatted, potentially read from a database
var article = {
title: {
en_US: "Article Title",
fr_FR: "Titre de l\'Article"
},
content: {
en_US: "Content of the Article.",
fr_FR: "Contenu de l\'Article."
}
}
// simple function to write the info to the page
function get_i18n(item, lang) {
document.write(article[item][lang]);
}
var lng; //global variable
if (localStorage.getItem('lng') == null) { //if I have no language saved just load the English language
lng = 'en_US';
localStorage.setItem('lng', lng);
}
if(localStorage.getItem("lng") == 'en_US'){
lng = 'en_US';
}
if(localStorage.getItem("lng") == 'fr_FR'){
lng = 'fr_FR';
}
console.log(lng);
function get_i18n(item, lng) {
document.write(article[item][lng]);
}
</script>
<div class="story">
<h1 class="title"><script>get_i18n('title',lng);</script></h1>
<p class="content"><script>get_i18n('content',lng);</script></p>
</div>

Categories