JS/HTML - Removing item before querying again - javascript

I have some code that grabs images from an API and it all works fine however, I can't figure out how to remove the original query before the other is displayed.
Open to other methods as well.
<html>
<body>
<div>Stock History Graph :</div>
<form>
<input type="text" value="" id="imagename"/>
<input type="button" id="btn" value="Update" />
</form>
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://chart.finance.yahoo.com/z?s=' + val +'.AX'+'&t=6m&q=l&l=on&z=s&p=m50,m200"',
img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
}
</script>
</body>
</html>

Create the img variable outside of the onclick function, then in the onclick function all you have to do is set the src of the image.
Right now you're creating a new element every time you click the button.

Check if Image already there just update src, no need to create tag again.
document.getElementById('btn').onclick = function() {
var val = document.getElementById('imagename').value,
src = 'http://chart.finance.yahoo.com/z?s=' + val +'.AX'+'&t=6m&q=l&l=on&z=s&p=m50,m200"',
img = document.getElementById("chart-comp") || document.createElement('img');
img.id = "chart-comp"
img.src = src;
document.body.appendChild(img);
}
Check this fiddle

Related

Add localstorage link as a image src

Hello I have a local storage link that needs to be displayed as a img src. If the local storage link is google.com I want it to be displayed as a img src
code so far
<body>
<div id="result">
</div>
<img src="" id="photo" /> //this is the img element
<script>
if (typeof(Storage) !== "undefined") {
var name = localStorage.getItem('name');
var dataImage = localStorage.getItem('imgData');
document.getElementById("photo").innerHTML = localStorage.getItem("name"); //localstorage
} else {
document.getElementById("photo").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
I know this question is confusing but this is the best I could describe.
You can set the image src attribute to the value you get from local storage. (Assuming that's a path to an image)
You would not want to set the innerHTML of an img tag. Instead, use another element to display text.
<div id="result"></div>
<img src="" id="photo" /> //this is the img element
<div id="msg"></div>
<script>
if (typeof(Storage) !== "undefined") {
var name = localStorage.getItem('name');
var dataImage = localStorage.getItem('imgData');
var imageName = localStorage.getItem("name");
var imageEl = document.getElementById("photo");
imageEl.src = imageName
} else {
document.getElementById("msg").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

Draw image to canvas with Pixabay API (Jquery)

The JSFIDDLE
Here is my problem:
I want to draw the image in the second line of the console when I double click on "Get JSON DATA", in my canvas.
I hope that was clear.
I think it's a bit difficult...
Here is my code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<canvas id="test1" width="200px" height="200px"> </canvas>
<input id="urlBanner" type="text" style="width:450px;" maxlength="100">
<button type="button" value="Get JSON Data" onclick="getUrlBanner()">Get JSON data</button>
<script>
function getUrlBanner()
{
var urlBanner = document.getElementById("urlBanner").value;
console.log(urlBanner);
var urlAPI = "https://pixabay.com/api/?key=10642718-3227f97c509ef5fe89537eec9&q=";
//var full = "full:" + urlBanner;
//console.log(full);
$(document).ready(function(){
$("button").click(function(){
fetch(urlAPI+urlBanner+"&image_type=photo")
.then(res => res.json())
.then((out) => {
var img = out.hits[0].largeImageURL;
document.getElementById('test1').src = img;
console.log(img);
console.log("full : " + urlAPI+urlBanner+"&image_type=photo");
}).catch(err => console.error(err));
});
});
}
$(document).ready(function() {
$('#test1').each(function() {
var myCanvas = document.getElementById('test1');
var ctx = document.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img[0],10,10);
};
img.src = 'UrlBanner';
});
});
</script>
</body>
</html>
My API works properly, that's ok.
In fact, the problem is really here I think
$(document).ready(function() {
$('#test1').each(function() {
var myCanvas = document.getElementById('test1');
var ctx = document.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img[0],10,10);
I can't get it...
The jpg file in console need to appear in my canvas.
Thanks in advance,

Upload Image Preview code created by Button doesn't preview the image. Javascript/HTML

So basically i'm stuck. I created a simple upload image button that allows me to preview the image file that i uploaded. I also created a button that creates another upload image button the button is called "Try It". My first upload image button, previews the image correctly, but when i push the "Try It" to create another upload image button and upload another image, it does not preview on the additional upload image button. I just want to know how i can fix it. Below is the full code:
function myFunction() {
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= "previewFile()";
document.getElementById("wtf").appendChild(x);
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
document.getElementById("preview").appendChild(y);
}
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile()">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>
First of all element.onchange takes a function and not a string i changed that also since you need to show different previews with different buttons you need a way to distinguish between them. I am creating a global variable i to keep track of it and passing it to the previewFile function as a parameter.
Here is the code:
var i = 0;
function previewFile(index){
var preview = document.querySelectorAll('img'); //selects the query named img
var file = document.querySelectorAll('input[type=file]')[index].files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview[index].src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
function myFunction() {
i++;
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
y.height = 200;
document.getElementById("preview").appendChild(y);
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= function(){previewFile(i)};
document.getElementById("wtf").appendChild(x);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile(0)">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>

Using Google Images API

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>

how can i get the height and width of image without page refresh in file tag? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
get image height and width in file tag using javascript
how can i get the height and width of image without page refresh in file tag?
<HTML>
<HEAD>
<TITLE></TITLE>
<script language="javascript">
function getW(){
var theImg = document.getElementById('testimg');
alert(theImg.width);
}
function getH(){
var theImg = document.getElementById('testimg');
alert(theImg.height);
}
</script>
</HEAD>
<BODY>
<input type="file" id="testimg"/>
<input type="button" value="get Width" onclick="getW()"/>
<input type="button" value="get Height" onclick="getH()"/>
</BODY>
</HTML>
i get the image height and width of image using php code, but that time page will be refreshed, without page refresh i get image size but not a height and width....
You can upload file through iframe and after iframe reloaded get image width/height. In modern browsers you can use FileReader API:
<input type="file" id="files" multiple/>
<script type="text/javascript">
function handleFileSelect() {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', theFile.name, '"/>'].join('');
document.body.appendChild(span);
var img = span.getElementsById('img');
img.onload = function() {
alert(img.src, img.offsetWidth, img.offsetHeight);
document.body.removeChild(span);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
There is an excellent post about reading file in javascript.

Categories