Javascript can't get width of object image - javascript

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);
})

Related

Checking if image exists before executing code

I have an array of image links that I'm getting from reddit, but some image urls are broken. I want to skip over broken image links.
This thread suggested using .width to see if an image exists. I tried using this answer to wait for image links to load before executing code but it's not working, it's skipping right over my if(this.width>0) check.
var imgLinksArray = Array.from(imgLinks);
document.getElementById('photoGrid').innerHTML = "";
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
var img = new Image();
img.onload = function() {
console.log(this);
console.log(this.src + " Width: " + this.width);
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
if (this.width > 0) {
console.log(this.width);
if (workingImgLink.search("webm") >= 0) {
document.getElementById('photoGrid').innerHTML += '<video autoplay loop class="box-wrapper"> <source type="video/webm" src= "' + workingImgLink + '" data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></video>';
} else {
document.getElementById('photoGrid').innerHTML += '<div class="box-wrapper"> <div data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></div></div>';
}
}
}
}
img.src = workingImgLink;
var bgImgWidth = img.width;
var bgImgHeight = img.height;
}
I only want to execute the innerHTML code if I know the image exists. Any suggestions about how to go about this?

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

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 = "" >';

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 - 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