Javascript to search images via Google - javascript

I'm working on a uni project: we are making a webstite for restaurant reviews by programming a server in Java and then linking it to html via Rythm Engine.
Now, restaurant owners will have to be able to create their restaurant's page on the site, and I would like said page to include at least one picture of the place. Uploading an image would involve php, which is outside of the scope of this project (mainly focused on Java). I want to include a script in the html that searches Google for the restaurant name and just grabs one picture off the internet. I found a handy snippet for finding a somewhat random image, too bad the API is not working anymore. Who's willing to help?
<html>
<head>
<title></title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(OnLoad);
var search;
//i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
var keyword = 'mountains';
function OnLoad()
{
search = new google.search.ImageSearch();
search.setSearchCompleteCallback(this, searchComplete, null);
search.execute(keyword);
}
function searchComplete()
{
if (search.results && search.results.length > 0)
{
var rnd = Math.floor(Math.random() * search.results.length);
//you will probably use jQuery and something like: $('body').css('background-image', "url('" + search.results[rnd]['url'] + "')");
document.body.style.backgroundImage = "url('" + search.results[rnd]['url'] + "')";
}
}
</script>
</head>
<body>
</body>
</html>

Related

I'm trying to preview random photos on the site's share link

I used this function in js to open the variable in the head of the html, I don't know if there is a solution or if there is another way to do it.
function randomlink() {
var links = new Array(3)
links[0] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr.jpeg"
links[1] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr0.jpeg"
links[2] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr1.jpeg"
var num = Math.round(Math.random() * 2))
}
randomlink()
In html <meta property="og:image" content=links[num]/>
"Metadata is used by browsers (how to display content or reload page), search engines (keywords), and other web services."
So changing it after the page has loaded will be useless. You will need to do this server-side wherever the content is being served from.
But if you want to try anyways, you will need to include more javascript in order to have a dynamic link. I can think of a couple ways to do it but I think your best bet will to be to just append the entire meta tag on load.
<script type='javascript'>
function escreverLinks() {
var links = [
"https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr.jpeg",
"https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr0.jpeg",
"https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr1.jpeg"
];
var numero = Math.round(Math.random() * 2));
document.head.append('<meta property="og:image" content="'+ links[numero] +'"/>')
}
document.onload(function(){
escreverLinks()
})
</script>

Insert Google Block Ads with Javascript

I have a site with many pages and I want to start with Google Ads on it... so I want to insert ads to all the pages, but I want to find a good way... I don't want to add the code manually in all the files... so I tried to build a function to add the google's adsense block after some paragraphs using javascript:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXX" crossorigin="anonymous"></script>
var display_block = '<ins class="adsbygoogle"' +
'style="display:block"' +
'data-ad-client="ca-pub-XXXXX"' +
'data-ad-slot="xxxxxxxxxx"' +
'data-ad-format="auto"' +
'data-full-width-responsive="true"></ins>' +
'<script>' +
'(adsbygoogle = window.adsbygoogle || []).push({});' +
'</script>';
var afterparagraph1 = document.getElementById('article').getElementsByTagName('p')[0]
afterparagraph1.insertAdjacentHTML('afterend', display_block );
var afterparagraph3 = document.getElementById('article').getElementsByTagName('p')[3]
afterparagraph3.insertAdjacentHTML('afterend', display_block );
Well the code is added (I can see when inspect with console) but the ads doesn´t appear... but if I insert the code manually inside each html file it appears... :(
Do you know what I am doing wrong?
Thanks for your time :)

Use javascript to get a random image from Google images

I have this idea for my website that every time you visit the page, the background will be different. I want to get literally any picture from Google images and place it as my website's background using Javascript.
Basically every time you refresh the page a script will fetch a random picture from Google images and place it as the background or maybe at least download the picture.
How should I do this, or is it even possible?
It can be done via Google Images though much customization is required so the script behaves as you intended (including setting up a delay to handle rate-limiting; Google has a rate-limit of 64 items per search request over API) here is a basic example using Google Images api:
<html>
<head>
<title></title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(OnLoad);
var search;
//i suggest instead of this to make keywords list so first to pick random keyword than to do search and pick random image
var keyword = 'mountains';
function OnLoad()
{
search = new google.search.ImageSearch();
search.setSearchCompleteCallback(this, searchComplete, null);
search.execute(keyword);
}
function searchComplete()
{
if (search.results && search.results.length > 0)
{
var rnd = Math.floor(Math.random() * search.results.length);
//you will probably use jQuery and something like: $('body').css('background-image', "url('" + search.results[rnd]['url'] + "')");
document.body.style.backgroundImage = "url('" + search.results[rnd]['url'] + "')";
}
}
</script>
</head>
<body>
</body>
</html>
However may I suggest instead: Random images from flickr, here is another basic code for that (sky is the limit):
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
var keyword = "mountains";
$(document).ready(function(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: keyword,
tagmode: "any",
format: "json"
},
function(data) {
var rnd = Math.floor(Math.random() * data.items.length);
var image_src = data.items[rnd]['media']['m'].replace("_m", "_b");
$('body').css('background-image', "url('" + image_src + "')");
});
});
</script>
</head>
<body>
</body>
</html>
although not technically what was asked, this could help give some structure to the randomness -- you could compose a couple dictionaries, of verbs, nouns, adjectives.. and mad-lib it up with a random adjective-noun verbing, (ie, fat bulldog running) then query google with that search, and pick a random picture from the results. this way, you can potentially reduce the inappropriate results, and also allow selection of specific dictionaries based on themes the user has selected perhaps. (ie, changing the available nouns based on user's likes)

Rotating logo in html/javascript

im trying to use html and javascript to create a rotating logo on my site.
I want it to rotate on page load, and load them randomly.
Ive tried SO MANY THINGS! that i found on google, and i cant seem to get it to work. Im trying to avoid using php to do it.
i want to be able to have the random image in a tag like below, (if possible)
<img src="" />
So, just to sum it up.
I want to use "html" and "javascript" to create a script that everytime a page is refreshed, it loads a new logo from a directory on my server.
EDIT: what i have tried
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite(myImage)
</script>
You should avoid using document.write. Instead put an id attribute on the img tag, and retrieve it using document.getElementById. You can make it refresh at intervals using the setInterval method:
<img id="logo" />
<script type="text/javascript">
var logos = ["logo1.png", "logo2.png", "logo3.png"];
var currentLogoIndex = 0;
function updateLogo() {
document.getElementById('logo').src = logos[currentLogoIndex];
currentLogoIndex++;
currentLogoIndex %= logos.length;
}
window.setInterval(updateLogo, 1000);
updateLogo();
</script>
you can store the pathes in an array and select them by using random index.
$(document).ready(function() {
var src = ['path1.jpg', 'path2.jpg', 'path3.jpg', 'path4.jpg', 'path5.jpg', 'path6.jpg', 'path7.jpg', 'path8.jpg', 'path9.jpg'];
$('img').attr('src', src[Math.floor(Math.random()*10)]) // it returns a number between 0 and 10
});
You know, there is a jQuery plugin for this which utilizes CSS transformations.
http://www.zachstronaut.com/posts/2009/08/07/jquery-animate-css-rotate-scale.html
I am Resorting to php guys.
<img src="/images/logo/<?php $random = rand(1,3); echo $random; ?>.png" alt="LOGO!!!!" />
works perfectly :)
<html>
<body>
<h1>Random logo From List</h1>
<script type="javascript>
Array.prototype.random = function () {
return this[ parseInt( Math.random() * this.length ) ];
}
var myImage=[
"logo1.png",
"logo1.png",
"logo1.png",
"logo1.png"
].random()
document.wite("<img src='" + myImage + "' />)
</script>
<h2>Hoo just got a random logo</h2>
</body>
</html>
Looks like this was what you tried for:
For a bit of explanation using document.write and document.getElement:
When you write inline code like above you can use document.write, it will just add the texts just after </h1> like a normal "print" operation.
Once you use it after document is loaded, it clears everything and overwrites whole thing.
If you want to change the document after it is loaded, you have to edit the DOM, the document is represented as DOM after its loaded. In that case you should use different DOM manipulation functions like
document.getElementById('logo-image').src = myImage;

Check if image exist

I use the following code to refresh an image in the browser. I just want to modify the code in order to first check if the image exists and then display the image. If the image does not exist I will only refresh the image to the previous version of the picture. Can someone point me how to accomplish this using javascript or jquery?
<html>
<head>
<script language="JavaScript">
function refreshIt(element) {
setTimeout(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
refreshIt(element);
}, 500); // refresh every 500ms
}
</script>
</head>
<body>
<img src="swt.png" name="myCam" onload="refreshIt(this)">
</body>
</html>
Edited: I need a combination of the already implemented functionality plus the file checking.
Functionality:
if image exist
refresh image
else
show cached image
Something like this:
$('#image_id').error(function() {
alert('Image does not exist !!');
});

Categories