Detecting image width via JavaScript when maxWidth is used - javascript

Consider this code:
var img = new Image();
img.onload = function() {
console.log(this.width);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
document.body.appendChild(img);
This will print out the image width (800) correctly. But if I apply a max-width using CSS:
img {max-width: 400px}
Test case: http://jsfiddle.net/MSjnM/
The JS code above will print out 400 instead. That is a bit confusing, as one would think that the width attribute represents the original image width, not the computed width.
Now to something even more confusing, if I append the image in the onload event after the width detection I get a different result:
var img = new Image();
img.onload = function() {
console.log(this.width);
document.body.appendChild(img);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
Test case: http://jsfiddle.net/MSjnM/2/
This will print out 800 instead, even though the CSS has applied. I assume it’s because the image is appended after I detected the width and that the max-width will be applied as soon as the image is inserted into the DOM.
OK, so if I want to get the original image size, no matter when or if the IMG element is inserted in the DOM or whatever CSS styles has been applied, how would I do that fail-safe?

For me:
in IE9, Opera, Safari(PC), FF and chrome the naturalWidth/naturalHeight-properties return the desired values
http://jsfiddle.net/MSjnM/5/

Load the image independently into a new Image object and get the width there:
var img = new Image();
img.src = 'http://placehold.it/350x150'
console.log(img.width);

Related

Delay between appendChild and actually becoming visible in Firefox

I tried adding a preloading function to my JS application. Basically it should only continue when all images are ready to display. Waiting for image.onload is the first step, but Firefox also needs some time appending the image to the document. In the following example the red background should not be visible because in theory the image is already there.
document.body.style.margin = "0";
document.body.style.background = "#000";
var img = document.createElement("img");
img.style.width = "100%";
img.onload = function()
{
// Add the image
document.body.appendChild(img);
// Then set BG to red - which should not be visible
document.body.style.background = "#F00";
}
img.src = "https://upload.wikimedia.org/wikipedia/commons/9/9d/Wikidata_Map_July_2017_Huge.png";
However in this example the red background is visible (up to 2 seconds on my system). I guess Firefox requires certain CPU power to append and shrink the image to 100% width. The problem didn't appear in Chrome or Safari.
How can I detect if the image is actually visible or still being processed?

How can I change the size of an image without cropping?

I have an image source:
var _img = <img src="../images/yadayada.jpg">
And I want it enlarge it or shrink it without cropping it, but I'd rather not grab the element after and change the css.
I tried:
_img.height = 200;
and
_img.style.height = 200
But the first crops it, and the second does nothing.
Style values need units so the style setting would be like this:
_img.style.height = "200px";
This will change the scaled size of the image. If you only set just the height or just the width, then the other should scale to maintain the aspect ratio. You will have to make sure that the HTML layout the image is positioned in is flexible and can handle the image changing size.
Image resize demo: http://jsfiddle.net/jfriend00/K8GJQ/
It's a little hard to tell if you're trying to change an existing image or set dimensions for a new image you're trying to create...
The statement var _img = <img src="../images/yadayada.jpg"> won't do anything by itself except cause your JS to fail to load (it's just a string, and is missing surrounding quotes and semicolon).
If you're trying to target an image that's already in the HTML, give its <img> tag a unique ID that you can target, and then set the width or height.
In the HTML: <img id="yadayadaImage">
In the JS:
var myImage = document.getElementById('yadayadaImage');
myImage.style.width = "200px";
Setting only style.width OR style.height here should keep the image from being cropped, since the other dimension should expand automatically. If it's still cropped check the parent element's width & height attributes, because that may be what's restricting the size.
.
If you're actually trying to create a new image w/specific source and dimensions, what you had above won't work. You need to create a new<img> element with those attributes, then append it to the document.
var targetDiv = document.getElementById("myPhotoDiv");
var imgTag = document.createElement('img');
imgTag.id = "yadayadaImage";
imgTag.className = "uncroppedImage";
imgTag.src = "../images/yadayada.jpeg";
//you COULD set height & width properties here, but that's what CSS is for.
imgTag.style.width = "200px";
targetDiv.appendChild(imgTag); //add the new img to the page
The best approach, but which you said you didn't want to do, is to use CSS and create a class that you can reuse for other images where you don't necessarily know the specific width or height.
.uncroppedImage{
width:100%;
}
Better setup an id for your image like this
<img id="myImg" src="../images/yadayada.jpg">
and use the script below
var myImg = document.getElementById('myImg');
if(myImg && myImg.style) {
myImg.style.height = '200px';
}

Resizing background images

This is really for informational and learning purposes while learning more about JavaScript and CSS. I have a local browser index page that I wanted to rotate the background image onload. After looking around and playing with different solutions, I settled on this for the basic rotate functionality:
<html>
<head>
<script language="javascript" type="text/javascript">
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
document.body.style.background = "url(" + img + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
</script>
</head>
<body onload="rotate()">
</body>
</html>
During the process, before I just set the backgroundSizeas cover to fill the window, I was playing with the idea of resizing the images before setting them as the background image after they are selected from the array.
I have done a lot of searching, and the only real working solutions I have found rely on selecting the element by ID, but that also requires that the image has an ID associated, such as in the IMG property in the HTML code. Here the image is selected and set in the JavaScript with CSS.
I have tried setting the image dimensions with img.width / img.height and img.style.width / img.style.height, as well as a few other random solutions I have come across, but whenever I try to change these the image either does not change or it does not show at all.
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
image = rsize(img);
document.body.style.background = "url(" + image + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
function rsize(image)
{
image.style.width = "300px";
image.style.height = "300px";
return image;
}
I know I am probably doing something wrong here. Is there a way, in this circumstance, that I can resize these images? Or is there a better way to construct this?
Thanks in advance.
You must set image.style.width and image.style.height on an actual image DOM object, not on the URL as you are currently trying to do.
As an image object is not used for background images, you can't really directly do what you're trying to do for a background image.
You could use the CSS background-size property, but that is fairly new and is not supported in versions of IE prior to IE9. If you were using that, you would set the actual size for that, not "cover".
You could also use an actual DOM image and then present that DOM image as centered in your page if that's what you're really trying to do.
For example, here's how you create a DOM image object, assign it a URL, set it's size and insert it into your page:
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var imgURL = imgArray[aImg];
var img = new Image();
img.src = imgURL;
img.style.width = "300px";
img.style.height = "300px";
img.id = "centeredImage";
document.body.appendChild(img);
You could then use CSS to position is in the center of your page if you wanted.
Working demo here: http://jsfiddle.net/jfriend00/jqMtV/
No, you have no <img> elements you could (re)size (btw, they would not need ids to be selectable). Your use of rsize(imgArray[aImg]) operates on the array members, which are strings and not DOM elements, so setting values on their non-existent style property would throw an error.
Yet, you're already on the right way with using the backgroundSize style property. Just don't set it to cover, but to the size you need!
document.body.style.backgroundSize = "300px 300px";
If you would want to use a <img> element, add this at the end of your <body>:
<img src="some.jpg" style="position:fixed; z-index:-1; width:100%; height:100%" />

JavaScript: Image doesn't scale in IE when dynamically added

when I dynamically add an image to a div the image doesn't scale when you resize the window in Internet Explorer.
I think it's more clear if I show two really simple examples:
The following example doesn't use JavaScript it's just plain html and it does what I want.
http://www.friendly-stranger.com/halp/ie-width/index.html
The next one uses JavaScript and if you resize the width of your browser window the image doesn't scale only the width gets smaller.
http://www.friendly-stranger.com/halp/ie-width/bad.html
This is a screenshot of both examples:
(source: friendly-stranger.com)
The JavaScript code I use:
<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
$('div').append(img);
});
</script>
<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
img.style.height = 'auto';
$('div').append(img);
});
</script>
try this, i hope it'll work

remote image properties using jquery

Currently i am trying to get remote image width/height. I am developing a link sharing module something like when you paste a link on facebook, you can see title, description and images.
So i tried using php getimagesize to get image width/height its very slow.
So i am thinking of using jquery solution to get remote image width/height so that i can filter image width less then 100px.
I am new in jquery/javascript
I tried something like
var img = $('#imageID');
var width = img.clientWidth;
var height = img.clientHeight;
$('#info').html(width+'.. height: '+height);
Its not working and return undefined .. height: undefined
Any help is appreciated.
Thank you
Try this:
var img = new Image();
img.src = 'http://your.url.here/image.png';
img.onload = function() {
$('#info').text('height: ' + img.height + ' width: ' + img.width);
};
This approach would let you get the image info without having to have an <img> tag at all. Now, perhaps you want the image to be on the page, so you'd do what #patrick suggests in that case.
If you're trying to get the width and height of the image in the client side, you can use jQuery's .width() and .height() methods.
Example: http://jsfiddle.net/aeBWQ/
$(window).load(function() {
var img = $('#imageID');
var width = img.width();
var height = img.height();
$('#info').html(width+'.. height: '+height);
});
Doing $(window).load() will ensure that the images are loaded before getting the height/width.

Categories