Replacing an image from external source on click JS beginner - javascript

Fairly new to JS, trying to build a tool for the company that i work for, that can pull the image from the supplier website when user types in a product number, the code below somewhat works but the image doesn't get replaced when entering a new number.
HTML:
<input id='pCOde' placeholder='Code?'>
<button onclick='addImg()'> Click me </button>
<p id='hImg'></p>
Javascript:
const pCode = document.getElementById("pCode").value;
function addImg() {
const img = new Image();
img.src = 'https://SupplierWebsite/pics/' + pCode.value + '.JPG';
document.getElementById('hImg').replaceWith(img);
img.style.height = 'auto';
img.style.width = '85%';
}
Eventually wanted to pull more data from the supplier site, such as product title and price but this seems even trickier.

It will help if you can share what kind of value you are hoping to get from pCode. But try using this, it will work.
let pCode = document.getElementById("pCode").value;
function addImg() {
var img = new Image();
img.src =
`https://SupplierWebsite/pics/${pCode}.JPG`;
document.getElementById('hImg').replaceWith(img);
img.style.height = 'auto';
img.style.width = '85%';
}

You are already getting .value in let pCode = ... line. So there is no need to pCode.value again, in img.src.
let pCode = document.getElementById("pCode").value;
function addImg() {
var img = new Image();
img.src =
'https://SupplierWebsite/pics/' + pCode + '.JPG';
document.getElementById('hImg').replaceWith(img);
img.style.height = 'auto';
img.style.width = '85%';
}

Related

Js/Jquery how to remove previous image thumbnail when choose another image?

I'm doing an upload function that will allow the user to upload a chosen image to the server, and it is supposed to show a thumbnail of the current image. But when another image is chosen, it will add in the newer image thumbnail, and wouldn't remove the older image thumbnail.
So, how do I remove the previous image thumbnail and replace it with the newer one?
Here is my javascript code:
function previewFiles() {
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 200;
image.title = file.name;
image.style.marginTop = '10px';
image.style.marginRight = '10px';
image.style.borderRadius = '3px';
image.style.marginBottom = '220px';
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
And here is my HTML code:
<input type="file" id="browse" accept='.jpeg, .png, .jpg' onchange='previewFiles()' name="image" />
<div id='preview'></div>
Thanks in advance!
You need to remove all the children before adding new one.
reader.addEventListener("load", function () {
var image = new Image();
image.height = 200;
image.title = file.name;
image.style.marginTop = '10px';
image.style.marginRight = '10px';
image.style.borderRadius = '3px';
image.style.marginBottom = '220px';
image.src = this.result;
//removes all children (images)
preview.childNodes.forEach(c => preview.removeChild(c));
preview.appendChild(image);

JavaScript array for an image gallery with next and prev functions

var spanishAdventure = new Array();
spanishAdventure[0] = new Image();
spanishAdventure[0].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756508_1743696655674610_7179458580676129491_o.jpg?_nc_cat=0&oh=f16a2edf4ee735e66b6dab095b7fb43c&oe=5B6B32B3';
spanishAdventure[1] = new Image();
spanishAdventure[1].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26758659_1743696569007952_4447096103197624856_o.jpg?_nc_cat=0&oh=a7f015a6709fa9a26f06b07fe9782999&oe=5B6A180E';
spanishAdventure[2] = new Image();
spanishAdventure[2].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678421_1743695449008064_7298258449829506874_o.jpg?_nc_cat=0&oh=d8fb71ad599a0a630f4d118c1d8be6ca&oe=5B6E0AFD';
spanishAdventure[3] = new Image();
spanishAdventure[3].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678110_1743696009008008_4042393389305650172_o.jpg?_nc_cat=0&oh=7d6afafd399c4a2d5d8f0747d59d8353&oe=5B73557C';
spanishAdventure[4] = new Image();
spanishAdventure[4].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756324_1743697449007864_8430059194945119796_o.jpg?_nc_cat=0&oh=5c93856d22087dbf550fc98dfd7a79ce&oe=5B5FBF15';
spanishAdventure[5] = new Image();
spanishAdventure[5].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678350_1743697612341181_2805503461338827658_o.jpg?_nc_cat=0&oh=1e6d3b0c44b783742de688cedacccc20&oe=5B6E31BF';
spanishAdventure[6] = new Image();
spanishAdventure[6].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26841396_1743696739007935_7256143030060966136_o.jpg?_nc_cat=0&oh=d0b9cbe4f3920af54083ea12d2d19b40&oe=5B63A5E7';
var imageCount = 0;
var totalImage = spanishAdventure.length -1; //array length starting from 0
var img = document.getElementById('mySlides'); //HTML img element which image will be displayed
function imagePrev() {
imgCount-- ;
img.src =spanishAdventure[imageCount].src;
if (imageCount < 0) {
img.src = spanishAdventure[totalImage].src;
break;
}
}
function imageNext() {
imgCount++ ;
img.src =spanishAdventure[imageCount].src;
if (imageCount > totalImage) {
img.src = spanishAdventure[0].src;
break;
}
}
Hi Guys,
I'm currently trying to create an image gallery using Javascript image array and functions that will be called upon to create a gallery in an image element in my original HTML file (not shown). Do you see anything wrong with the js syntax and code for the next and previous functions as they seem to not work when called upon in the html file. I'm a newbie so some enlightening pointers would be fab.
mySlides is the id for an HTML img element.
Cheers,
Liam
As #Titus said, change imageCount to imgCount, or vice-versa
Remove break; from imagePrev and imageNext. It's not doing anything useful.
Build logic to keep imageCount (or imgCount) within the range of your image array.
You don't need to instantiate images to store your source urls. The urls are just text, so they could be put directly into an array, like spanishAdventure = ['urlText1', 'urlText2', ...]
var spanishAdventure = new Array();
spanishAdventure[0] = new Image();
spanishAdventure[0].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756508_1743696655674610_7179458580676129491_o.jpg?_nc_cat=0&oh=f16a2edf4ee735e66b6dab095b7fb43c&oe=5B6B32B3';
spanishAdventure[1] = new Image();
spanishAdventure[1].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26758659_1743696569007952_4447096103197624856_o.jpg?_nc_cat=0&oh=a7f015a6709fa9a26f06b07fe9782999&oe=5B6A180E';
spanishAdventure[2] = new Image();
spanishAdventure[2].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678421_1743695449008064_7298258449829506874_o.jpg?_nc_cat=0&oh=d8fb71ad599a0a630f4d118c1d8be6ca&oe=5B6E0AFD';
spanishAdventure[3] = new Image();
spanishAdventure[3].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678110_1743696009008008_4042393389305650172_o.jpg?_nc_cat=0&oh=7d6afafd399c4a2d5d8f0747d59d8353&oe=5B73557C';
spanishAdventure[4] = new Image();
spanishAdventure[4].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26756324_1743697449007864_8430059194945119796_o.jpg?_nc_cat=0&oh=5c93856d22087dbf550fc98dfd7a79ce&oe=5B5FBF15';
spanishAdventure[5] = new Image();
spanishAdventure[5].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26678350_1743697612341181_2805503461338827658_o.jpg?_nc_cat=0&oh=1e6d3b0c44b783742de688cedacccc20&oe=5B6E31BF';
spanishAdventure[6] = new Image();
spanishAdventure[6].src = 'https://scontent.flhr4-1.fna.fbcdn.net/v/t31.0-8/26841396_1743696739007935_7256143030060966136_o.jpg?_nc_cat=0&oh=d0b9cbe4f3920af54083ea12d2d19b40&oe=5B63A5E7';
var imageCount = 0;
var totalImage = spanishAdventure.length -1; //array length starting from 0
var img = document.getElementById('mySlides'); //HTML img element which image will be displayed
function imagePrev() {
imageCount > 0 ? imageCount-- : imageCount = 6;
img.src =spanishAdventure[imageCount].src;
}
function imageNext() {
imageCount < 6 ? imageCount++ : imageCount = 0;
img.src =spanishAdventure[imageCount].src;
}
<img id="mySlides" />
<button onClick="imagePrev()">Prev</button>
<button onClick="imageNext()">Next</button>

image name and dimension mismatched on fileselect through loop

As per my previously posted question below which i got answered. I need to get image name along with dimension.
I already tried lot of things to get them but the name and dimension is getting mismatched
How to read(image data / dimension / filesize / name) multiple images on file select?
below is the complete function to get image file information.
fileSelect.addEventListener("change", getSomeFile, false);
function getSomeFile(ev){
var file= ev.target.files;
if (file) {
for(var i=0,f; f = file[i]; i++){
if(!f.type.match('image.*')){continue;}
(function(f){
var reader = new FileReader();
reader.readAsDataURL(file[i]);
reader.onload = function () {
var img = new Image();
img.onload = function() {
var span = document.createElement('span');
span.innerHTML = ['<img id="thumb" src="', img.src,'"/>'].join('');
document.getElementById('mid').appendChild(span, null);
var fileName =f.name;
var fileSize =Math.round(f.size/1024)+' KB';
var imageWidth = img.width;
var imageHeight = img.height;
};
img.src = reader.result;
};
})(file[i]);
}
}
fileSelect.value='';
}

How do I load a local image using JS?

I want to load two separate images in my script. I've accomplished it using:
<img src="iphone4.png" id="img1">
<img src="screenshot.png" id="img2">
<script>
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
</script>
Problem here though is that the images should not be visible on the page but are when loaded using markup. I simply want to load them through the script without first having to add them in the markup. I realize this is an extremely trivial problem, but searching for a solution has given me nothing.
I tried this approach:
window.onload = function () {
var img1 = "iphone4.png";
var img2 = "screenshot.png";
But this did not work.
Can someone with some common JS sense please give me some input on this issue.
EDIT :
So this is how the markup/JS looks now, the images are still displayed and the final merge of the images won't show. The error I get is:
IndexSizeError: Index or size is negative or greater than the allowed amount
[Stanna vid fel]
var image1 = context.getImageData(0, 0, width, height);
And this is the syntax:
<body>
<img src="" id="img1">
<img src="" id="img2">
<p>Blended image<br><canvas id="canvas"></canvas></p>
<script>
window.onload = function () {
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
img1.src = "iphone4.png";
img2.src = "screenshot.png";
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = img1.width;
var height = img1.height;
canvas.width = width;
canvas.height = height;
var pixels = 4 * width * height;
context.drawImage(img1, 0, 0);
var image1 = context.getImageData(0, 0, width, height);
var imageData1 = image1.data;
context.drawImage(img2, 73, 265);
var image2 = context.getImageData(0, 0, width, height);
var imageData2 = image2.data;
while (pixels--) {
imageData1[pixels] = imageData1[pixels] * 0 + imageData2[pixels] * 1;
}
image1.data = imageData1;
context.putImageData(image1, 0, 0);
};
</script>
You can create an Image without having the actual tag in the markup:
var img = new Image();
img.src = 'iphone4.png';
//use img however you want
Hope this helps.
window.onload = function () {
var img1 = new Image();
var img2 = new Image();
//EDIT2 you can hide img, or simply not add them to the DOM...
img1.style.display = "none";
img2.style.display = "none";
img1.src = "iphone4.png";
img2.src = "screenshot.png";
EDIT: DO NOT DO THAT and your images won't be displayed
document.body.append(img1);
OR
document.getElementById("myID").append(img2);
"What I'm doing is merging two images using JS"
Your problem is probably due to the fact that you are trying to draw images that have not been loaded yet. To circumvent this issue, you could create the images dynamically and set their src attribute to start loading the image and listen to the image's load event to know when they are fully loaded so that you can perform the merge safely.
I have not tested the code, but it should give you the idea.
var images = [
'iphone4.png',
'screenshot.png'
],
len = images.length,
i = 0,
loadedCount = 0,
img;
for (; i < len; i++) {
img = document.createElement('img');
//listener has to be added before setting the src attribute in case the image is cached
img.addEventListener('load', imgLoadHandler);
img.src = images[i];
images[i] = img;
}
function mergeImages() {
var img1 = images[0],
img2 = images[1];
//do the merging stuff
}
function imgLoadHandler() {
if (++loadedCount === len) {
mergeImages();
}
}
There is a way with HTML5, but it would still require the user to have dropped the file into a drop target or use a box.
Using the File API you can read files, and potentially decode them.
Actually reading the file blob and displaying it locally may be tricky though. You may be able to use the FileReader.readAsDataURL method to set the content as a data: URL for the image tag.
example:
$('#f').on('change', function(ev) {
var f = ev.target.files[0];
var fr = new FileReader();
fr.onload = function(ev2) {
console.dir(ev2);
$('#i').attr('src', ev2.target.result);
};
fr.readAsDataURL(f);
});​
see the working fiddle here :
http://jsfiddle.net/alnitak/Qszjg/
using jquery:
$('#my_image').attr('src','image.jpg');
using javasript:
document.getElementById("my_image").src="image.jpg";
just check path to your image
Write the below code in head block
<script>
window.onload = function () {
document.getElementById("img1").src="iphone4.png";
document.getElementById("img2").src="screenshot.png";
}
</script>
This will work
Thanks

JavaScript imagemap code doesn't work

What is wrong with this code? Why is my imagemap not working?
function createimg()
{
var img = new Image();
img.src='link/to/image';
img.alt='Next image'; img.id = 'span1'; img.style.zIndex = 10;
img.style.position = 'absolute';
img.style.display='block';
img.style.top = '130px';
img.style.padding='10px';
img.style.left='440px';
img.usemap='#testmap';
img.className ='dynamicSpan';
document.body.appendChild(img);
var mymap = document.createElement('map');
mymap.name = 'testmap';
document.body.appendChild(mymap);
var areatag = document.createElement('area');
areatag.shape = 'rect';
areatag.coords = '900,200,1100,1000' ;
areatag.href = 'http://www.google.com';
mymap.appendChild(areatag);
document.body.appendChild(areatag);
return img;
}
UPDATE:
I reconstructed my code like this, but it is still not functional:
function createimg()
{
var img = new Image();
img.src='link/to/image';
img.alt='Next image';
img.id = 'span1';
img.style.zIndex = 10;
img.style.position = 'absolute';
img.style.display='block';
img.style.top = '130px';
img.style.padding='10px';
img.style.left='440px';
img.usemap='#testmap';
img.className ='dynamicSpan';
var mymap = document.createElement('map');
mymap.name = 'testmap';
mymap.id = 'testmap';
var areatag = document.createElement('area');
areatag.shape = 'rect';
areatag.coords = '0,0,500,500' ;
areatag.href = 'http://www.google.com';
areatag.target = '_blank';
//append area to map
mymap.appendChild(areatag);
// append map to document
document.body.appendChild(mymap);
//append image to document
document.body.appendChild(img);
return img;
}
here's the solution:
you should use
img.setAttribute("usemap", '#testmap')
instead of:
img.usemap = "#testmap"
You have created element instance "mymap", but didn't added (not appended) it to the document, as you did it for "img" (appendChild).
document.createElement(name) creates an instance of element, but not appends it to the document.
it may be that the order in which you do things is not good.
i think you should:
create img element (+set its attrs)
create map element (+set its attrs)
create area element (+...)
append area to map
append map to document
append image to document
In addition to Viktor's answer:
img.usemap='#testmap';
...
mymap.name = 'testmap';
You will probably need to give mymap an id of "testmap"

Categories