Get the size of image in Javascript - javascript

I can't get the dimensions of image. Here is the code...
The HTML:
<img class="edit-img about-img" src="images/box-model.jpg">
The JavaScript:
function getDimension () {
var img = document.getElementsByClassName('about-img');
var width = img.clientWidth;
var height = img.clientHeight;
}
window.onload = getDimension;
It say's that the variable 'width' & 'height' is undefined. I also tried using img.width & img.height.

getElementsByClassName() does just that - get elements by class name.
It doesn't return a single Node - even if there is only one element with that class name - but rather a NodeList of all the elements.
What you'd be looking for is something like this:
var img = document.getElementsByClassName('about-img')[0];
var width = img.clientWidth;
var height = img.clientHeight;
However, hard-coding the index like this assumes that there is only one image with that class name. That may not always be true, and if it isn't, then just taking the first element probably won't get you what you're looking for. In this case, I would give the image an ID:
<img class="edit-img about-img" id="my-image" src="images/box-model.jpg">
After you've done this, you can use getElementById(), which works as you expected getElementsByClassName() to:
var img = document.getElementById('my-image');
var width = img.clientWidth;
var height = img.clientHeight;

Select the element by it's id attribute, to get the image you are referring to.
function getDimension () {
var img = document.getElementById('myId');
var width = img.clientWidth;
var height = img.clientHeight;
console.log(width);
console.log(height);
}
window.onload = getDimension();
<img id="myId" class="edit-img about-img" src="http://via.placeholder.com/350x150">

Fiddle example
function getDimension () {
var img = document.getElementById('imageId');
var width = img.clientWidth;
var height = img.clientHeight;
alert(width);
}
window.onload = getDimension();
Just have to use an ID instead of class name in your JavaScript. Check the fiddle.

Related

JavaScript - Get width of element during css transition

I want to display an element's width in javascript. This part is already working, but here is my issue :
When the element's width is animated, during the animation I want to see the real element's width, and not the final element's width.
I'm working with Angular, and what I wanted to do was possible by including JQuery using the function $(el).width() but I want to remove JQuery uses.
I already tried (assuming el is a HTML element) :
el.offsetWidth
el.clientWidth
el.scrollWidth
el.getBoundingClientRect().width
Some time ago I faced the same issue, with images who are not loaded yet and had the size of 0. I fixed the problem with using the following code to get the original image size. Be sure you continue your code inside the onload function
var image = new Image();
image.onload = function() {
// set its dimension to target size
var width = image.width;
var height = image.height;
};
image.src = el.img;
It is also possible to do this with a base64 string if needed
var image = new Image();
image.onload = function() {
// set its dimension to target size
var width = image.width;
var height = image.height;
};
image.src = "data:image/jpg;base64," + img;

Add value to :after element in jquery or javascript?

Hy, I have all the code, but I have no clue how to add it to :after elements. It's probably easy,here's the code:
window.onload = function() {
var imageSrc = document
.getElementById('bg_head')
.style
.backgroundImage
.replace(/url\((['"])?(.*?)\1\)/gi, '$2')
.split(',')[0];
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
asp=height / width;
$('#bg_head').append('<style>#bg_head:before{padding-top:'asp';}</style>');
}
You probably see what I'm trying to do. Add the asp calculated value to the padding-top or bottom of a :after element. But I don't know how to fix the code. I just need to convert everything to jquery I think?
Thanks

Firefox gives wrong values for image width and height

From a html5 drag'n drop plugin, i'm getting a data uri of dropped images (or from a file input..).Then i'm setting it as an image src :
$("#preview").attr("src",image);
Now, i need to make some actions depending on the image dimensions. I tried this by two ways :
1) - By getting the image height and width from the uri data directly (i got this piece of code from here
var curHeight;
var curWidth;
function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
curHeight = newImg.height;
curWidth = newImg.width;
}
getImgSize(The_data_uri);
2) by testing on the created image on the html :(here i created two booleans)
var lt = function(v1, v2){
return v1 < v2;
}
var gt400 = (lt(400,parseInt($("#preview").css('width').replace('px', ''))) && lt(400,parseInt($("#preview").css('height').replace('px', ''))) && !window['cropIsOn'] );
var eq400 = (parseInt($("#preview").css('width').replace('px', ''))==400 && parseInt($("#preview").css('height').replace('px', ''))==400) && !window['cropIsOn'] ;
On chrome i always got the correct dimensions and therefore tests on dimentions are corrects. However, on firefox it's not correct (i got wrong width and height values). by the way, i'm not trying with different image format for each time(i'm only using jpg images).
i wish to understand why firfox isn't stable about reading height and width.Cheers!
-EDIT-
the image which i'm trying to get its dimensions is inside a hidden div
<div id="prview_img_wrap" style="position:absolute;top:465px; left:200px;z-index:8; width:100px;height:100px;overflow:hidden;margin-left:5px; border:2px dashed white; visibility:hidden;">
<img src="" id="preview" />
</div>
The height and width of the image are only available after the image is loaded. so this is the correct way:
var curHeight;
var curWidth;
function getImgSize(imgSrc){
var newImg = new Image();
newImg.onload = function () {
curHeight = this.height;
curWidth = this.width;
};
newImg.src = imgSrc;
}

jQuery code to find the image width and height using image source

In our site we are accessing our images or the image source is like
<img src="image_manage.php&type=resize&id=12" />
My issue is, to get the image height and width using this source in jquery.
I write a code to get the width and height
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
var width = photograf.width;
var height = photograf.height;
But I got the value zero for both height and width what is the issue?
Try this code:
var oImage = new Image();
oImage.onload = function(){
this.width// width of loaded image
}
oImage.src = '/path/to/image.gif';
Or something like that is better:
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
Try with this
width = $("img").attr('width'); //can also $("img").width();
hight = $("img").attr('height'); //can also $("img").height();
you can try this
width = $("img").prop('width');
hight = $("img").prop('height');
Dont forget to put js code in load or document ready events
$(document).ready(function(){
var height = $('img').prop('height');
var width= $('img').prop('width');
alert('Height :'+height+' AND '+'width :'+width);
});
here is the running example
Example
jsfiddle
Use jQuery width() and height() functions:
jQuery(function(){
var $width = jQuery("img").width();
var $height = jQuery("img").height();
});
The image isn't loaded yet when you ask for its size. The onLoad method is helpful for this purpose.
photograf = new Image();
photograf.src = '/image_manage.php&type=resize&id=12';
photograf.onLoad = function(){
var width = this.width;
var height = this.height;
};
You'll have to wait for the image to load in order to detect it's size.
$("#imgElement").attr('src',photograf.src).load(function(){
var w = $("imgElement").width();
var h = $("imgElement").height();
});
Here I am setting the src parameter of the image and using jQuery's load() function to detect when the image has been successfully loaded.
Reference -
load()

Using javascript to derive height of image when only resized width is explicitly given in html

Forgive my ignorance of javascript, but I'm trying to create a simple image hover that enlarges the image when you hover your mouse over it. (And no, I don't want to use JQuery. I want to learn this directly in javascript!) My problem is that only the width is specified in the html. The height is omitted so that the image displays proportionally on the page. When I hover over the image with my mouse, the javascript works fine in IE, but in FF, Chrome, Safari, etc. img.offsetHeight gets assigned 0 rather than a proportion of img.offsetWidth.
<script type="text/javascript">
var img=document.getElementById('imageid');
var thiswidth=img.offsetWidth;
var thisheight=img.offsetHeight;
var ratio=thisheight/thiswidth;
var bigwidth=600;
var bigheight=bigwidth*ratio;
function bigImg(x) {
x.style.width=bigwidth;
x.style.height=bigheight;
}
function normalImg(x) {
x.style.width=thiswidth;
x.style.height=thisheight;
}
</script>
<img id="imageid" onmouseover="bigImg(this)" onmouseout="normalImg(this)" src="myimage.jpg" alt="image" width="200" >
As you can see from the img tag, height is inferred proportional to width by not being specified. Can someone tell me how I can use javascript to derive thisheight from thiswidth?
this will work for you in all ie FF, Chrome, Safari, etc
<html>
<body>
<img id="imageid" onmouseover="bigImg(this)" onmouseout="normalImg(this)" src="C810623C.gif" alt="image" width="200" >
<script type="text/javascript">
var img = document.getElementById('imageid');
var normsizeimg = img.style.width;
var bigwidth = 600;
function bigImg(x)
{ x.style.width = bigwidth; }
function normalImg(x) { x.style.width = normsizeimg; }
</script>
</body>
</html>
this is why it's easier to do such things with jquery, some browsers keep dimension values in offsetWidth others don't;
here's a tip of how you can get across this problem
var thiswidth=img.offsetWidth;
var thisheight=img.offsetHeight;
//it's non IE browser
if(XMLHttpRequest){
var thisheight=img.clientHeight;
var thiswidth=img.clientWidth;
}
This works fine for me on Firefox (I don't have access to other browsers right now, sorry):
<img id="imageid" src="myimage.jpg" alt="image" width="200" >
<script type="text/javascript">
var img = document.getElementById('imageid');
img.onload = function(){
var thiswidth = img.offsetWidth;
var thisheight = img.offsetHeight;
var ratio = thisheight/thiswidth;
var bigwidth = 600;
var bigheight = bigwidth*ratio;
img.onmouseover = function bigImg() {
img.style.width = bigwidth;
img.style.height = bigheight;
}
img.onmouseout = function normalImg(x) {
img.style.width = thiswidth;
img.style.height = thisheight;
}
};
</script>
The main differences between this code and yours is that:
I'm only accessing the element after it is declared
I'm only accessing its properties after the image loads
I'm also only adding the onmouseover and onmouseout attributes later because it makes the HTML look cleaner, but that's optional.
Update: actually, adding the event handlers later isn't optional, because they use the calculated bigwidth and bigheight, which are only available after the image loads.

Categories

Resources