Why does a dynamically added image always have an offsetWidth of 0 - javascript

I am adding an image via Javascript.
The image could be of any size and I'd like to get the size (width and height).
The issue is, the offsetWidth and style.width is always 0
Here is some code to replicate
const container = document.getElementById("container");
const img = document.createElement("img");
img.src = "https://images.freeimages.com/images/large-previews/56e/hibiscus-1393855.jpg";
document.body.appendChild(img);
const result = document.getElementById("result");
result.innerText = (img.offsetWidth + " " + img.style.width);
<div id="container">
</div>
<div id="result">
</div>
The above works. I am running what appears to be near identical code but, it always shows an offsetWidth of 0
How do I get the image width and height

You have to wait for the image to load to be able to get its actual size:
const container = document.getElementById("container");
const img = document.createElement("img");
img.addEventListener('load', function() {
document.getElementById("result").innerText = img.offsetWidth;
});
img.src = "https://images.freeimages.com/images/large-previews/56e/hibiscus-1393855.jpg";
document.body.appendChild(img);
<div id="container">
</div>
<div id="result">
</div>

Related

No image width, canvas / constructor javascript [duplicate]

I am adding an image via Javascript.
The image could be of any size and I'd like to get the size (width and height).
The issue is, the offsetWidth and style.width is always 0
Here is some code to replicate
const container = document.getElementById("container");
const img = document.createElement("img");
img.src = "https://images.freeimages.com/images/large-previews/56e/hibiscus-1393855.jpg";
document.body.appendChild(img);
const result = document.getElementById("result");
result.innerText = (img.offsetWidth + " " + img.style.width);
<div id="container">
</div>
<div id="result">
</div>
The above works. I am running what appears to be near identical code but, it always shows an offsetWidth of 0
How do I get the image width and height
You have to wait for the image to load to be able to get its actual size:
const container = document.getElementById("container");
const img = document.createElement("img");
img.addEventListener('load', function() {
document.getElementById("result").innerText = img.offsetWidth;
});
img.src = "https://images.freeimages.com/images/large-previews/56e/hibiscus-1393855.jpg";
document.body.appendChild(img);
<div id="container">
</div>
<div id="result">
</div>

jQuery - How do I get the image width of an online image?

I have a project which consists of a HTML, JS and CSS file.
When I open the project in my browser I have an input field (url input), a button and a canvas.
After I insert the URL of an image in the input field and click the button, I want the canvas to resize according to the width and height of the image. Of course, I also want the image to be displayed in the canvas.
Note: Later I want to add a functionality where someone can resize the image with a slider. This means that I really have to save the width of the image in a variable.
So, my main problem is that I don't know how to get the width of that image.
The last thing I tried is the following:
$('#btn_load').click(function () {
input_url = $('#input_url');
var url = input_url.val();
var img_width = url.width;
...
});
Would be glad about some help here, since I tried a lot of stuff in the last hours :)
EDIT:
I now also tried the following:
var inputURL, imgWidth;
inputURL = $('#input_url');
$('#btn_load').click(function () {
var url = inputURL.val();
var img = new Image();
img.src = url;
img.onload = function () {
imgWidth = img.width;
};
canvas.css({
'background-image': 'url(' + url + ')',
//'background-size': 'cover',
});
//This is just to check the width value
inputURL.val(imgWidth + url);
});
But still doesn't work.
This will get the img width and height in the global variables 'imgHeight' and 'imgWidth' It will also display the image on the screen, width a slider to make it bigger or smaller,
the min and max value of the input type range are dynamically set to the original width and height divider by 2 or for the maximum multiplied by 2.
Javascript:
var imgHeight;
var imgWidth;
var img = new Image();
function LoadImage() {
input_url = $('#input_url');
img.src = input_url.val();
//img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
//alert(imgHeight + " : " + imgWidth);
//Now set the image to html
document.getElementById("imgID").src=img.src;
//Now set the dimensions.
$("#imgID").css({'height' : imgHeight+'px', 'width' : imgWidth+'px'});
//Now set the range min to imgwidth / 2. and the max to imgwidth * 2
document.getElementById("range").min = imgWidth / 2;
document.getElementById("range").max = imgWidth * 2;
document.getElementById("range").value = imgWidth;
}
}
function ChangeImageSize(value) {
//Calculate new height so the image doesn't get stretched.
newHeight = value / imgWidth * imgHeight;
//Set the new width and height
$("#imgID").css({'height' : newHeight+'px', 'width' : value+'px'});
}
HTML
<button onclick="LoadImage()">click me</button>
<input type="range" id="range" oninput="ChangeImageSize(this.value)">
<input type="text" id="input_url">
<img id="imgID">
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.js" > </script>
<script>
function loadUrl() {
//You can get the value of your url_input and use it instead.
var url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"; //You can take it from your input_url
$("#img-size").attr("src", url);
};
function imageLoaded(sender){
alert($(sender).width() + 'x' + $(sender).height());
}
</script>
</head>
<body>
<img src="" id="img-size" onload="imageLoaded(this);">
<input type="button" onclick="loadUrl();" id="btn_load" value="Load" />
</body>
</html>
You should load the imag to get its natural width and height :
var img = new Image();
img.src = $('#input_url').val();
img.onload = function () {
imageWidth= img.naturalWidth;
imageHeight = img.naturalHeight;
...
}

Get Image Dimensions (Height and Width) Js or jquery

I have searched for this, but every time I implement the code it return 24 as height and width as 237 when I upload 400X400 image.
$(document).on('change','#tt' , function(){
var img = document.getElementById('tt');
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
alert(nheight)
alert(nwidth)
});
<input type="file" id="tt" name="tt" >
Is anyone know how can I get 400 as height and 400 as width in alert box when I upload 400X400 image. Any help is really much appreciated.....
Onchange event of file upload creating a Image object and attach uploaded file object as src to image object and then onload event of image object find height and width of image.
Please check below snippet for more understanding.
var _URL = window.URL || window.webkitURL;
$(document).on('change','#tt' , function(){
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert("width : "+this.width + " and height : " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="tt" name="tt" >
var nheight = img.clientHeight;
var nwidth = img.clientWidth;
will just get you the dimension.
Refer this -
Try
var x = document.getElementById("myImg").naturalWidth;
the naturalHeight property to return the original height of an image, or the height property to set or return the value of the height attribute of an image
http://www.w3schools.com/jsref/prop_img_naturalwidth.asp

How do I get this JavaScript slideshow to work?

I am trying to create an image slideshow. I added the 7 images into the array. The slideshow starts with image0.jpg and when the user clicks on the right arrow, I want the javascript to insert the next image in the array (image1.jpg). The problem is that the img variable is not going past 1. Can someone help me get this slideshow to work?
HTML
<h1>Swap Image Experiment</h1>
<div class="slideshow">
<div id="myImages">
<img id="test" src="images/image0.jpg">
</div>
<div class="arrows">
<div id="left" onClick="swapPicture(-1)"></div>
<div id="right" onClick="swapPicture(+1)"></div>
</div>
</div>
<script src="js/script.js"></script>
</body>
JavaScript
var dImages = new Array();
var numImages = 6;
for(i=0;i<numImages;i++)
{
dImages[i]=new Image();
dImages[i].src="images/image"+(i)+".jpg";
}
function swapPicture(target) {
img = 0;
image = document.getElementById("test")
img = img + target;
console.log(img);
image.src = "images/image"+(img)+".jpg";
}
You should change img from a local variable to a global variable. Now every time when you execute that function, img will be set to 0. So change it to
var img = 0;
function swapPicture(target) {
image = document.getElementById("test")
img = img + target;
console.log(img);
image.src = "images/image"+(img)+".jpg";
}
Along with Dacaspex answer, you should remember to loop back to pic 5 (assuming 0-5 for your 6 images) if they go left instead of right. Also to loop to 0 if they go right when at 5...
var img = 0;
function swapPicture(target) {
image = document.getElementById("test")
img = img + target;
console.log(img);
if(img < 0)
{
img = 5;
}
else
{
if(img > 5)
{
img = 0;
}
}
image.src = "images/image"+(img)+".jpg";
}

Get the images dimension from html

I have two images in two different section and div.I want to get the original dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event);"/>
</section>
js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
function OnImageLoad(evt) {
var img1 = evt.currentTarget;
var img2 = evt.currentTarget;
// what's the size of this image
var w1 = $(img1).width();
var h1 = $(img1).height();
var w2 = $(img2).width();
var h2 = $(img2).height();
You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
counter++;
sizes.push({
height: h,
width: w
});
if (counter == 2) {
callAnotherFunction(sizes)
}
}
prepending the variables with a custom value should make it possible.
HTML
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event,1);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event,2);"/>
</section>
JS
function OnImageLoad(evt, pre) {
var img = evt.currentTarget;
// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");
Ive not tested this though.
function OnImageLoad() {
var img1 = document.getElementById("Image1");
var img2 = document.getElementById("Image2");
// what's the size of this image
var w1 = img1.width;
var h1 = img1.height;
var w2 = img2.width;
var h2 = img2.height;
}
Html:
<section id ="hi">
<img id="Image1" src = "images/hi.png"/>
</section>
<section id = "bye">
<img id="Image2" src = "images/hi.png"/>
</section>
Call this function on window.onload=OnImageLoad();
function OnImageLoad(evt) {
//This function will be called on each image load and will iterate all the image inside this dom
var images = $('img');
for(var i =0 ;i<images.length; i++) {
// what's the size of this image
var w = $(images[i]).width();
var h = $(images[i]).height();
//For each file you will have width and height of the image
console.log('width of image-'+i+': ',w);
console.log('height of image-'+i+': ',h);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<section id ="hi">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-green-orbs-icons-business/103491-3d-glossy-green-orb-icon-business-tool-screwdriver.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-orange-orbs-icons-business/105429-3d-glossy-orange-orb-icon-business-tool-hammer4-sc44.png" onload = "OnImageLoad(event);"/>
</section>
</body>
</html>
enter link description here

Categories