I'm trying to use Google's Images API to search an image and put it into my html document as a div. This is what I have so far, but nothing seems to be appearing. This is parts from http://code.google.com/apis/imagesearch/v1/devguide.html. This is my first time using an API, so I'm not sure what is really going on.
<html>
<head>
<title>Art Project FTW</title>
</head>
<body>
<br>
<br>
<form name="upload" method="post" action="parse_image.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
</form>
<script type="text/javascript" src="https://www.google.com/jsapi?key=xxx"></script>
<script type="text/javascript" charset="utf-8">
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('h2');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
}
}
function onload() {
// Our ImageSearch instance.
var imageSearch = new google.search.ImageSearch();
// Restrict to extra large images only
imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
google.search.ImageSearch.IMAGESIZE_MEDIUM);
// Here we set a callback so that anytime a search is executed, it will call
// the searchComplete function and pass it our ImageSearch searcher.
// When a search completes, our ImageSearch object is automatically
// populated with the results.
imageSearch.setSearchCompleteCallback(this, searchComplete, [imageSearch]);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
}
google.setonloadCallback(onload);
</script>
</body>
</html>
Thanks in advance!
It can't work because you are looking for a HTMLElement that has the ID='content', you haven´t anyone element with that ID
Try putting your js functions within <head></head>
Related
I'm working on a project for a friend and he wants a pure walk cycle with only HTML/JS (no CSS). So I've tried to work it out but the image only shows up on the webpage.
It doesn't move when I press any buttons or anything at all.
Please show me where I went wrong. I'm used to using HTML and CSS but this is my first JS so I don't know many terms.
How it appears in the website:
My code (HTML + JS):
<!DOCTYPE html>
<html>
<head>
<title>Javascript Animation</title>
<script language="Javascript">
<!--
var walker = new Array(6);
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5) curWalker == 0;
else ++curWalker;
document.animation.src = walker[curWalker].src;
}
-->
</script>
</head>
<body>
<p><img src="walk1.png" name="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval('marathon(),100);">
<input type="button" name="stop" value="stop" onclick="clearsetInterval(startwalking);">
</form>
</body>
</html>
Here it is how I did it get to work (I had to build my simple images with Paint in order to use them in the animation):
<html>
<head>
<title>Javascript Animation</title>
</head>
<body>
<p><img src="walker1.png" id="animation"> </p>
<form>
<input type="button" name="walk" value="walk" onclick="startWalking=setInterval(marathon,100);">
<input type="button" name="stop" value="stop" onclick="clearInterval(startWalking);">
</form>
<script>
var walker = [];
var curWalker = 0;
var startWalking;
for(var i=0; i<6; i++) {
walker[i] = new Image();
walker[i].src = "walker"+i+".png";
}
function marathon() {
if(curWalker == 5)
curWalker = 0;
else
++curWalker;
document.getElementById("animation").src = walker[curWalker].src;
}
</script>
</body>
</html>
I had to correct several typos/mistakes:
Put the JS just before the </body> closing tag
The first paramether of setInterval() must be a function name, so it must be marathon (you had 'marathon(); note that leading single quote)
In order to get the image to be substituted it is better to access the element though Id instead of name attribute. So I changed the image to <img src="walker1.png" id="animation"> (animation is now the Id) and accessed it through document.getElementById("animation")
Now the animation starts... but stops to the last image instead of restarting to the first.
That was because you used to check the curWalker variable instead of performing an assignment: I put curWalker = 0; instead of curWalker == 0;
Almost there. The loop is complete, but the stop button doesn't work. Two typos are preventing this to work:
clearsetInterval doesn't exist. The function to be called is clearInterval
Javascript is a case sensitive language. You use startwalking variable as a parameter, but the correct variable name is startWalking. So you have to correct the onclick event writing clearInterval(startWalking); instead of clearsetInterval(startwalking);
Your animation is now complete.
Note: as correctly noted by #Mike 'Pomax' Kamermans, nowadays you can avoid the use of onclick as you can attach events to the document (such as "click") by using document.addEventListener.
I have a google sheet, I want to prompt a user to select ranges to get information from, store that into an array, and then create a chart in an html popup. I have read a bit about the google.script.run functionality, and understand that without the withSuccessHandler(HTMLFunction).FunctionToCall() syntax at the end, the HTML script moves onto the next line. I have a .gs file below, and an .html file, and I was able to get the graph to work when I just entered a static array in my .gs function. However, I seem to be struggling with how to return focus to the editor to get a range, and then to bring the HTML dialog box with the chart back up and get the right data to the function that plots the chart. I saw here that I could use the google.script.host to call the editor.focus() function so the user can now select cells, but I can't seem to get the focus back to the HTML popup without calling the HTML file all over again. Here is my .gs function:
function RetrieveData(){
var ss = SpreadsheetApp.getActive();
var sheets = ss.getSheets();
var s = sheets[1];
var UI = SpreadsheetApp.getUi();
var response = UI.prompt("Please enter the first cell in the category").getResponseText();
var ir = s.getRange(response);
var n= 0;
var stored = [];
stored.push(["Income Category", "Frequency"]);
while (ir.getValue()!= "") {
n = n +1;
ir = ir.offset(1, 0);
}
ir = ir.offset(-n,0)
for(i =0; i<n;i++) {
stored.push([ir.getValue(),ir.offset(n+2,0).getValue()]);
ir = ir.offset(1, 0);
}
return stored;
}
Here is my html that is within the body (Stack Overflow is a little strict, so I am not going to go through the trouble of showing all the HTML; this is just within the body and it is what is communicating with the .gs file):
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(getdata);
function getdata() {
google.script.run.withSuccessHandler(drawChart).RetrieveData();
google.script.host.editor.focus();
}
function drawChart(stored) {
//This apparently shows a log of the object
//console.log(stored);
var data = new google.visualization.arrayToDataTable(stored);
console.log(data);
var options = {'title':'Income',
'width':400,
'height':300,
'is3d':true};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.script.run.withSuccessHandler(drawChart).RetrieveData();
}
One last thing I tried was to call the
SpreadsheetApp.getUi().showModalDialog(html, "Title") function one more time, but without calling the html file all over again, and creating an endless loop, I don't seem to have a way to do that. Any idea how to accomplish this?
Here's a simple example of picking a range with a modeless dialog. With just a few extra features thrown in for good measure.
Code.gs:
function selRange()//run this to get everything started. A dialog will be displayed that instructs you to select a range.
{
var output=HtmlService.createHtmlOutputFromFile('pickRange').setWidth(300).setHeight(200).setTitle('Select A Range');
SpreadsheetApp.getUi().showModelessDialog(output, 'Range Selector');
}
function selCurRng()
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getActiveRange();
var rng0A1=rg0.getA1Notation();
rg0.setBackground('#777700');
return rng0A1;
}
function clrRange(range)
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getRange(range);
rg0.setBackground('#ffffff');
}
pickRange.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var grange='';
function selectRange()
{
$('#btn1').prop('disabled',true);
$('#btn2').prop('disabled',false);
google.script.run
.withSuccessHandler(setResponse)
.selCurRng();
}
function setResponse(r)
{
grange=r;
var msg='You have select the range ' + r;
$('#instr').css('display','none');
$('#rsp').text(msg);
}
function clearAndClose()
{
google.script.run.clrRange(grange);
google.script.host.close();
}
console.log('My Code');
</script>
</head>
<body>
<div id="rsp"></div>
<div id="instr">Please select your desired range.</div>
<input type="button" id="btn1" value="Range Selected" onClick="selectRange();" />
<br /><input type="button" id="btn2" value="close" onClick="clearAndClose();"; disabled="true" />
</body>
</html>
I have looked for duplicate questions, however many refer to adding data to XML
please forgive me if I have missed something here but I need some help
so far I have this:
html page
<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>
<p id="content"> Content </p>
</body>
</html>
controlpanelAdmin.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
controlpanelModerator.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
When the page loads, 'Admin Control Panel' is written into the fieldset tag
but is then replaced by: 'Moderator Control Panel'
I cannot for the life of me think how to append both lines (and maybe other data as well) into one element
When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'
That can't happen. Admin Control Panel should never appear in the page.
script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload.
script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
The page finishes loading
The load event fires
The function defined in script/controlpanelModerator.js is called
Don't assign values to window.onload. Use addEventListener instead.
addEventListener("load", function () { ... });
You've got two onload functions competing. Can you merge them into one function?
Hi all i want to document.write a hyperlink image inside getjson i tried the following but it doesnt work. could you guys tell me what is wrong with my document write?
<script>
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
document.write("<a id="ok" href="http://www.mysite.com/master.m3u8?+siteContents+"><img src="./playicon.jpg"></a>");
});
</script>
Hi all i want to document.write a hyperlink image inside getjson
You can't (not reasonably*). document.write only works during the initial parsing of the page. If you use it after the page finishes loading, it completely replaces the page.
Instead, interact with the DOM. Several ways to do that, but the most obvious based on your code is to have the anchor initially-hidden and then show it after filling in the text area like this:
$("#ok").show();
Full Example: Live Copy | Live Source
(I've changed the playicon.jpg to your gravatar, since otherwise it shows as a broken image on JSBin)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form name="myform">
<textarea name="outputtext"></textarea>
</form>
<a id="ok" style="display: none" href="http://www.mysite.com/master.m3u8?+siteContents+"><img src="http://www.gravatar.com/avatar/f69cfb4677f123381231f97ea1138f8a?s=32&d=identicon&r=PG"></a>
<script>
(function($) {
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents;
// shows the link
$("#ok").show();
});
})(jQuery);
</script>
</body>
</html>
* "not reasonably": IF your content were coming from the same origin as the document (it doesn't look like it is), you could do this with a synchronous ajax call. But that would be very bad design.
Please, use createElement instead of document.write
$.getJSON('http://anyorigin.com/get?url=http://www.somesite.com/handelit.ashx&callback=?', function(data){
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
//Create A-Element
var link = document.createElement('a');
link.setAttribute('href', 'http://www.mysite.com/master.m3u8?' + encodeURIComponent(siteContents) );
link.id = 'ok';
//Append A-Element to your FORM-Element
var myForm = document.getElementsByTagName('form')[0];
myForm.appendChild(link);
//Create IMG-Element
var img = document.createElement('img');
img.setAttribute('src', './playicon.jpg');
//Append IMG-Element to A-Element (id='ok')
link.appendChild(img);
});
I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>