Trying to use Javascript array to display Random images in <div> - javascript

I'm not well know about javascripts, got this code from a website.
Using javascript to display random images from array in div
javascript working fine.
But loaded images displays in random sizes
tried using css style and all css html image attributes to resize them but nothing works, as they are displayed directly through javascript
want something to resize them directly in javascript
code main :
<script>
var arrayImg = new Array();
arrayImg[0] = "a11.jpg";
arrayImg[1] = "a12.jpg";
getRandomImage(arrayImg, "");
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + alt = "" >';
document.writein(imgStr);
document.close();
}
</script>
code I used to resize image : (but didn't work) :
<script>
var arrayImg = new Array();
arrayImg[0] = "a11.jpg";
arrayImg[1] = "a12.jpg";
getRandomImage(arrayImg, "");
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var img.height = 4vw;
var img.width = 20%;
var imgStr = '<img src="' + path + img + img.height + img.width + alt = "" >';
document.writein(imgStr);
document.close();
}
</script>
even tried using : (but still didn't work)
document.writeln('<td' + '><imgstr"' + height="180" width="160" border="0" ><' + '/td>');

You have a few syntax error in getRandomImage function.
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
/*
1. variable name should not contain .
2. the width and height value should be quoted and placed in "style" attribute
*/
//var img.height = 4vw;
//var img.width = 20%;
var imgHeight = '4vw';
var imgWidth = '20%';
/* closed string quotations and placed data in the right attribute */
var imgStr = '<img src="' + path + img + '"'
+ ' style="height:' + imgHeight + ';width:' + imgWidth + ';'
+ ' alt="">';
document.writein(imgStr);
document.close();
}

You have several places where you didn't close quotation marks.
In code main:
var imgStr = '<img src="' + path + img + '"' + ' alt = "" >';
In resize code
var imgStr = '<img src="' + path + img + '" height="' + img.height + '" width="' + img.width + '" alt = "" >';

Related

What's causing Intersection Observer API to respond differently when replacing synchronous logic with asynchronous logic?

Context
I've used the "Intersection Observer API" to build an infinite scroll image gallery. Basically this API allows me to load more items when a certain dummy DOM element enters the viewport.
Prototype
Currently the prototype is implemented for an “iPhone X” (375x812) mobile device only. See: http://urbexco-acceptance.droppages.com/min_rep_ex_working (use Chrome DevTools 'inspect' device toolbar to select the right resolution). The image gallery is generated based on 57 items in the "database". When scrolling down, first 15 elements are loaded, then 15 more elements are loaded, then another 15 elements are loaded into the DOM, then another 10 elements are loaded, and finally 2 elements are loaded. When there are still more than 15 items left to be loaded, they are added using the following logic:
function addItems(n){
// Append new items to .items-wrapper
var items = document.querySelector('.items-wrapper');
for (var i = 0; i < n; i++) {
var url = 'https://img01.ztat.net/article/spp-media-p1/09742e38c25b3e1d9716e02f8e76e87d/89fc0bda6a2c446a8e9e0d8adbc9a4fe.jpg';
width = 170.5;
height = 246;
var newDiv = document.createElement('div');
newDiv.classList.add('item');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + width + '"' + "height=" + height + "/>";
}
}
Minimal Working Example (no mobile view possible)
https://jsfiddle.net/9jqgzymo/
Objective
Since image width and height are currently hardcoded, I am now trying to assign width and height dynamically based on the image url. I try to achieve this using the getMeta() function:
function addItems(n){
// Append new items to .items-wrapper
var items = document.querySelector('.items-wrapper');
for (var i = 0; i < n; i++) {
var url = 'https://img01.ztat.net/article/spp-media-p1/09742e38c25b3e1d9716e02f8e76e87d/89fc0bda6a2c446a8e9e0d8adbc9a4fe.jpg';
getMeta(url);
}
}
function getMeta(url){
var img = new Image();
img.onload = function(){
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
};
img.src = url;
}
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
Challenge
When implementing it this way, I see that - on initiation - already 30 items from the "database" where added to the DOM. Sometimes even all of them? Currently the non-working prototype is implemented for an “iPhone X” (375x812) mobile device only. See: http://urbexco-acceptance.droppages.com/min_rep_ex_not_working (use Chrome DevTools 'inspect' device toolbar to select the right resolution). For a minimal working example, see: https://jsfiddle.net/k3p20qno/
Key question
What is the reason that with my new implementation, on initiation, already 30 or more items are added to the DOM? How can I fix it?
Well the problem lies in here :
function getMeta(url){
var img = new Image();
img.onload = function(){
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
};
img.src = url;
}
Above code does an async operation with onload event. So it doesn't wait to image to be loaded.
If you turn this into a function that returns a promise you will get the result that you expect. And you should await where you call the function. That way when you add the intersection element it will add it as the last element of the items wrapper. If you don't await it will be added as the first element because the loading of the images will be async and will happen later.
function getMeta(url){
var img = new Image();
const p = new Promise(resolve =>{
img.onload = function(){
console.log( this.width+' '+ this.height );
res = calculateAspectRatioFit(this.width, this.height, 170.5, 246)
var newDiv = document.createElement('div');
newDiv.classList.add('item');
var items = document.querySelector('.items-wrapper');
items.appendChild(newDiv);
newDiv.innerHTML = "<img src=" + '"' + url + '"' + "width=" + '"' + res.width + '"' + "height=" + res.height + "/>";
resolve()
};
})
img.src = url;
return p;
}
Fiddle
Edit: Put the resolve() in the right position which is inside the load function

how to print multiple barcode images using jquery

I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.

Javascript can't get width of object image

I have the following code
var inputLocalFont = document.getElementById("image-input");
inputLocalFont.addEventListener("change",previewImages,false);
function previewImages(){
var fileList = this.files;
var anyWindow = window.URL || window.webkitURL;
for(var i = 0; i < fileList.length; i++){
var objectUrl = anyWindow.createObjectURL(fileList[i]);
$('.preview-area').append('<img class="resizeme" id="myImage" height="150" src="' + objectUrl + '" + title="' + fileList[i].name + ' ( ' + fileList[i] + ' "/>');
window.URL.revokeObjectURL(fileList[i]);
}
}
i can get image name for title by this code
fileList[i].name
but when i try to add width and height in title image by adding this code
fileList[i].width
fileList[i].height
it's give "undefined" result
i already try using fileList[i].naturalWidth
and it's give same result
what I'm missing?
FLOW
i try to created a multiple image preview before user press submit and upload image to server...i want every preview image has tooltip title which contains (name, width, height)
i already success get name in tooltip by
fileList[i].name
is it possible to get width and height of image too in tooltip title?
ADD EVENT LISTENER INSIDE LOOP
var inputLocalImage = document.getElementById("image-input");
inputLocalImage.addEventListener("change",previewImages,false);
function previewImages(){
var fileList = this.files;
var anyWindow = window.URL || window.webkitURL;
for(var i = 0; i < fileList.length; i++){
var objectUrl = anyWindow.createObjectURL(fileList[i]);
objectUrl.addEventListener("load", function() {
alert('objectUrl.width');
})
$('.preview-area').append('<img class="resizeme" id="myImage" height="150" src="' + objectUrl + '" + title="' + fileList[i].name + ' (s ' + fileList[i].clientWidth + ' "/>');
window.URL.revokeObjectURL(fileList[i]);
}
}
I already try add event listener in
objectUrl / filename[i]
with property
.width
.naturalWidth
.clientWidth
What I'm missing?
HTML
<div class="row">
<label for="image" class="control-label col-lg-3">Image<span class="required">*</span></label>
<div class="col-lg-8">
<input type="file" class="dimmy" id="image-input" multiple />
<div class="preview-area"></div>
</div>
</div>
preview-area class is my container for multiple image preview...i append it by this code
$('.preview-area').append('<img class="resizeme" id="myImage" height="150" src="' + objectUrl + '" + title="' + fileList[i].name + ' ( ' + fileList[i] + ' "/>');
see this example: http://jsfiddle.net/kevalbhatt18/pjf3uffs/3/
Note :In this Example I don't have multiple image so i get width and
height when we click on image
And for changing width use inputLocalFont.style.width = '500px';
And for getting Name of image :
var name = inputLocalFont.src;
var filename = name.split("/")[name.split("/").length-1];
var inputLocalFont = document.getElementById("image-input");
inputLocalFont.addEventListener("click", previewImages, false);
function previewImages() {
var width = inputLocalFont.clientWidth;
var height = inputLocalFont.clientHeight;
var name = inputLocalFont.src;
inputLocalFont.style.width = '500px';
alert("width:" + width + "height:" + height)
var filename = name.split("/")[name.split("/").length - 1];
console.log(filename)
}
You need to use an eventListener for the "load" event of the image object, only then you will be able to get the image's width.
img.createEventListener("load", function() {
alert(img.width);
})

Javascript - window.open() popup size issue

I am trying to display preloaded images in a newly created popup window. Here is the code:
HTML
<div id="hiddenImages" style="display: none;"></div>
<img src="SmallImage1.gif" width="196" height="130" border="0">
<img src="SmallImage2.gif" width="196" height="130" border="0">
JS
<script type="text/javascript">
preloadImages('BigImage1.png','BigImage2.png');
</script>
// PreLoadImages:
function preloadImages() {
var hiddenDiv = document.getElementById('hiddenImages');
var i;
var img;
for(i = 0; i < arguments.length; i++) {
img = document.createElement('img');
img.src = arguments[i];
img.id = arguments[i];
img.alt = '';
hiddenDiv.appendChild(img);
}
}
// OpenImage:
function OpenImage(element,e)
{
e.preventDefault();
var big_image = element.getAttribute("href");
var img = document.getElementById(big_image);
var top = (screen.height/2)-(img.height/2);
var left = (screen.width/2)-(img.width/2);
var str = "\"" + "width=" + img.width + ",height=" + img.height + ",top=" + top + ",left=" + left + ",status=0, scrollbars=0, resizable=0" + "\"";
alert(str);
var myWindow = window.open(img.src , "win1", str);
}
When I output 'str' variable in OpenImage() function, this code gives perfect dimensions of the big image. However, the size of popup window is always different than size of the image. IE stretches the popup window horizontally while Google Chrome stretches it vertically. In spite of the fact that both browsers show exactly the same dimensions for the image. And these dimensions of the image are actually being set as size of the pop up window.
Regards.
Try this out, also try to rename your variable top, I think javascript read this as a keyword.
var str = "width=" + img.width + ",height=" + img.height + ",top=" + tops + ",left=" + left + ",status=0, scrollbars=0, resizable=0 ";

jQuery/javaScript : images don't load

I have the following code:
all_images = new Array(Array);
$.get('../dotclear-files/themes/biblio/js/dynamic_ajax_php.php', function(data) {
var w = 0;
$(data).find('image').each(function() {
if (!all_images[w]) all_images[w] = new Array();
all_images[w]['url'] = $(this).find('url').text() + '#comments';
all_images[w]['src'] = $(this).find('src').text();
all_images[w]['title'] = $(this).find('title').text();
all_images[w]['width'] = $(this).find('width').text();
all_images[w]['height'] = $(this).find('height').text();
w = w + 1;
});
$("#carousel-comments").append('<ul></ul>');
for (x=0; x<3; x++) {
$('#carousel-comments ul')
.append('<li>')
.append('<a href="' + all_images[x]['url'] + '#comments" title="' + all_images[x]['title'] + '">')
.append('<img alt="' + all_images[x]['title'] + '" class="jcarousel-img jcarousel-img-' + x + '" width="' + all_images[x]['width'] + 'px" height="' + all_images[x]['width'] +'px" />')
.append('</a>')
.append('</li>');
var img = new Image();
$(img)
.load(function() {
$('.jcarousel-img-' + x)
.attr({'src': all_images[x]['src'], 'alt': all_images[x]['title']})
.fadeIn();
})
.attr('src', all_images[x]['src']);
}
$('#carousel-comments').jcarousel('reload');
}, 'xml');
The first part of this code loads images from a PHP script, that returns an XML file. This part works fine.
The issue comes with the 2nd part: $(img).load(...) It never displays my images.
This can be seen on my test page: it's the 3rd carousel, under the title named "C'est vous qui le dites!" We can see that the titles of the images are displayed... but the images themselves aren't loaded.
What am I doing wrong?
Thanx for any help!
I think you must append the <img> to the carousel.
$(img).appendTo($("#carousel-comments"));
Or something like this.
Edit after the comments exchange:
The element <IMG> in your LI are not the same that your var img = new Image. Then try something like this:
for (x=0; x<3; x++) {
var img = new Image();
img.load(function() {
$(this).fadeIn();
// Also, set your carousel here
});
img.attr('alt', all_images[x]['title'])
.attr('width', all_images[x]['width'])
.attr('height', all_images[x]['height'])
.addClass('jcarousel-img jcarousel-img-' + x)
.attr('src', all_images[x]['src']);
$('#carousel-comments ul')
.append('li')
.append('<a href="' + all_images[x]['url'] + '#comments" title="' + all_images[x]['title'] + '">')
.append(img);
}

Categories

Resources