I am very unexperienced in Javascript/Jquery therefore I use the JavaScript Load Image plugin to handle the front end of my image upload process.
The Problem: I would like to upload multiple images, not just one, and therefore also would like to display all the images, which are to be uploaded as a thumbnail. At the moment just one image is shown as a thumbnail.
The Fiddle: https://jsfiddle.net/r7s3n64b/1/ (displaying just one thumbnail)
HTML (the relevant parts)
<!-- FILE INPUT -->
<p><input type="file" name="images[]" id="upload-post-images" multiple></p>
<!-- THUMBNAILS -->
<div id="result" class="result">
<p>This only works in browsers with support for the URL or FileReader API.</p>
</div><br>
My attempt to loop through the to be uploaded images:
replaceResults = function (img) {
var content;
var imageFiles = document.getElementById("upload-post-images"),
filesLength = imageFiles.files.length;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0; i < filesLength; i++) {
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Die Bilddatei konnte nicht geladen werden.</span>');
} else {
content = $('<a target="_blank">').append(img)
.attr('download', currentFile.name)
.attr('href', img.src || img.toDataURL());
}
result.children().replaceWith(content);
if (img.getContext) {
actionsNode.show();
}
} // end for loop
},
I would be very thankful for any kind of help!!
=== E D I T ===
In your fiddle the thumbnails are placed after the closing form tag:
</form>
<img src="blob:https%3A//fiddle.jshell.net/001bd1f5-1cce-4618-bc83-9c8bd24f9e90" width="200" height="150">
<img src="blob:https%3A//fiddle.jshell.net/001bd1f5-1cce-4618-bc83-9c8bd24f9e90" width="200" height="150">
In my project (using your code) the thumbnail is placed within the result div:
<div id="result" class="result">
<a target="_blank" download="image.jpg" href="data:image/png;base64,iVBO3sSxiFIz6LUNoB9b27d/p9/HzNSojY7M+FCmPOnGAsrVBWlKSGsSfG4GBNOzbIWtW38xtqwSLsTpzHF7/N4n7PwQgrIo5fh...></a>
<canvas width="265" height="354"></canvas>
</div>
Is there any chance that you would happen to have an idea why this is or how I could change that?!
Thank you so much for your tremendous help!
You need to change your on change function to this:
document.getElementById('upload-post-images').onchange = function (e) {
for(i = 0; i<=e.target.files.length; i++)
{
loadImage(
e.target.files[i],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 200} // Options
);
}
};
Here is updated jsFiddle: https://jsfiddle.net/r7s3n64b/2/
Earlier your event handler looked like this:
document.getElementById('upload-post-images').onchange = function (e) {
loadImage(
e.target.files[0],
function (img) {
document.body.appendChild(img);
},
{maxWidth: 200} // Options
);
};
So beacuse of this line:
e.target.files[0]
You always pass only one image (first) from image array.
Enjoy! :)
UPDATE
Regarding your update - so basically it's all about the second parameter in loadImage function.
Change your upload-post-images change event like following.
document.getElementById('upload-post-images').onchange = function (e) {
$.each(e.target.files, function () {
loadImage(
this,
function (img) {
document.body.appendChild(img);
}, {
maxWidth: 200
} // Options
)
});
};
UPDATED FIDDLE
Related
I'm making a slideshow in javascript for a class assignment and I have the slideshow working but it's not displaying the images. I can see that the image icon changes but the actual image is not showing.
<script type="text/javascript">
//put images in array
var pics = new Array();
pics[0] = new Image();
pics[0].src = "images/forest.jpg";
pics[1] = new Image();
pics[1].src = "images/mountains.jpg";
pics[2] = new Image();
pics[2].src = "images/nature.jpg";
pics[3] = new Image();
pics[3].src = "images/snowtops.jpg";
var index = 0; //start point
var piclength = pics.length - 1;
function slideshow() {
document.slide.src = pics[index];
if (index < piclength) {
index++;
}
else {
index = 0;
}
}
function slide() {
setInterval(slideshow, 3000);
}
</script>
<body onload="slide()">
<h1>Nature Photography</h1>
<main>
<section>
<p>I am an enthusiastic about nature photography. Here is a slideshow of my
works.</p>
<aside> <img id="myImage" src="images/forest.jpg" name="slide" width="95%">
</aside>
First, I would put the script tag after your HTML. This will allow you to cache DOM elements without waiting for the "DOMContentLoaded" event or the "load" (window) event to be fired.
Second, you should cache the "myImage" element. Something like const slider = document.getElementById('myImage').
Third, check your console. Maybe your image URLs are wrong? And make sure your HTML is valid. From what you posted, you are missing a lot of things (doctype, html/head tags, you didn't close body tag and similar)
I want a gif to play when clicked, and to stop when clicked again. I'm following this method: http://www.hongkiat.com/blog/on-click-animated-gif/
So far, I have:
HTML
<figure>
<img src="test.png" alt="Static Image" data-alt="test.gif"/>
</figure>
<script src="playGif.js" type="text/javascript"></script>
playGif.js
(function($) {
// retrieve gif
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
// pre-load gif
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
// swap on click
$('figure').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
});
})(jQuery);
Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.
The gif does play on click, but if clicked again it reloads the gif instead of reverting to the png (at least in Chrome and Firefox. IE just does nothing on further clicks).
So here is the finished jsfiddle: https://jsfiddle.net/2060cm1c/
It is a simple variable swapping problem:
a=1;b=2;
a=b;// now a=2
b=a;// a=2, b=a=2
To solve it, you need a temporary variable:
a=1;b=2;
temp=a;a=b;
b=temp;
Now solve the OP's problem:
var temp=$img.attr('src');
$img.attr('src', $imgAlt).attr('data-alt', temp);
So, the problem is as easy as swapping 2 variables. You don't need the if to check the extension.
I am trying out a JavaScript where it takes Id of an image and onclick of the image it performs some function. But I have multiple Id's of same image where the id of the onclick'ed image should be processed by JavaScript and the operation should be performed.
Problem is I am not able to get the right id based on the click.
here is my code
1)myhtml
<div class="col-md-3 col-sm-6">
<div class="sub-process-block quantity">
<h3>choose quantity</h3>
<div id="example" onclick="changeImage()">
<img src="img/carton-empty.png" id="myImage">
<img src="img/carton-empty.png" id="myImage1">
<img src="img/carton-empty.png" id="myImage2">
</div>
</div>
2)javascript
<script>
function changeImage() {
var imageArray=["myImage","myImage1","myImage2"];
for(var i=0;i<imageArray.length;i++ ){
image = document.getElementById(imageArray[i]).onclick;
}
if(image.src.match("selected")) {
image.src="img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
Why don't you add an event listener to your images in JS? Then you can check if it's selected or not and update the source accordingly
// get all images and put them in an array
var images = [].slice.call(document.querySelectorAll('img'));
// loop through images and add event listener
images.forEach(function(image) {
image.addEventListener('click', onImageClick);
});
// on click, check if image is selected and update src
function onImageClick(e) {
var image = e.target;
if (image.src.match("selected")) {
// is selected, now unselected it and update src
image.setAttribute('src', 'img/carton-empty.png');
} else {
// is not selected, now select it and update src
image.setAttribute('src', 'img/carton selected.png');
}
}
https://jsfiddle.net/0qzdsf8r/4/
Inspect the image elements in the dev tools and see the class and src change.
Try this ;)
function changeImage(){
var imageArray = ["myImage", "myImage1", "myImage2"];
for(var i = 0; i < imageArray.length; i++){
var image = document.getElementById(imageArray[i]);
if(image.src.match("selected")){
image.src = "img/carton-empty.png";
}else{
image.src = "img/carton selected.png";
}
}
}
You placed condition outside for loop;
I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>
I'm using this code to build a gallery:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
[].forEach.call(image,function(x){
x.onmouseover = function(){
mainImage.src = x.src;
};
});
}
The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with
rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src
but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.
Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
mainImage.src = image[0].src; // Add this line (preload first image into main one)
function toMainImage() {
mainImage.src = this.src;
}
[].forEach.call(image,function(x){
x.addEventListener("mouseenter", toMainImage, false);
});
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">
<div class="thumbnails">
<img src="//placehold.it/200x200/cf5&text=1">
<img src="//placehold.it/200x200/f0f&text=2">
<img src="//placehold.it/200x200/444&text=3">
</div>