How can I get the size of images by javascript? - javascript

I am trying to get image size by javascript, for that I used offsetHeight, scrollHeight, clientHeight but none of these worked. The naturalHeight property worked but it return the actual size of image even if the image is resized by css. Strangely if I click the try button then the same code work well. Where did i wrong?
Please explain:
Why does the code work well when I execute it by clicking a button?
How can I get the image size when it is resized by css or screen size?
var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);
function test() {
var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);
}
<div class='container' style='width:40%;'>
<img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' />
</div>
<button onclick='test()'>try</button>

function test() {
var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);
}
<body onload="test();">
<div class='container' style='width:40%;'>
<img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' />
</div>
<button onclick='test()'>try</button>
</body>
Call the function in the onLoad event. This will ensure the assets of the page have loaded, including images,css.

1: by that time, the page has been loaded and the browser has painted the layout, so sizes exist.
2: Duplicate Question.
Google Query: dom image height
Top Result: How to get image size (height & width) using JavaScript?

Related

HTML Resize Div with Javascript

I am working on an online presentation editor.
I have a div (which should be the slide - the format is 16x9)
If the user decides to export it as pdf, the div should resize to 1920x1080, and then it should be exported (so that the pdf is not the same size as the user window, but always 1920 x 10800. My problem is, that if I set the width in JS like this:
$('#content').css('min-width', `1920px`);
$('#content').css('min-height', `1080px`);
$('#content').css('width', `1920px`);
$('#content').css('height', `1080px`);
only the container resizes, but the content doesn't.
This is what the slide looks like in the app
This is what the exported pdf looks like because the content doesn't resize.
If you have any idea, please let me know.
HTML:
<div style="background-color: green" id="content">
<h1 style="color: black">Hallo Welt</h1>
<p>Hallo 3CHIF!</p>
</div>
Well, maybe there's other solutions (or even better solutions), but I tought about scale(), this will scale the div and consequently, it's contents.
So, how I did it:
I estipulated the desired width and height (in your case, 1920x1080), then I got the div current size.
Divided the desired sizes by current sizes to get the "ratio", then used the CSS transform to set the new scale(x, y), as you can see in the below example.
You can base yourself in the code to get your solution
var desiredWid = 1920;
var desiredHei = 1080;
var theDiv = $("#content");
var currentWid = theDiv.width();
var currentHei = theDiv.height();
var ratioW = desiredWid / currentWid;
var ratioH = desiredHei / currentHei;
theDiv.css("transform","scale(" + ratioW + "," + ratioH + ")")
var currentSizes = theDiv[0].getBoundingClientRect();
console.log("Adjusted Size:", currentSizes.width + " x " + currentSizes.height)
#content {
width: 2500px;
height: 1200px;
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">Original Size: 2500x1200</div>
I used jQuery since I saw you are using, but you can do it with pure JS also.
try
#content{
width:100%;
height:100%;
}
if you want to have initiate max with or height you can add it to css too
then see if .css work or not
or must I say
then use js

how to get the height and width of image in javascript?

I have a code where I am trying to get all images tag height and width.
var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third', $(this)[0].height, $(this)[0].clientHeight, $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height')); });
Even i tried for img in loop.
tried the same with width , the result will be either 0 or undefined.
tried same thing for width.
Can you tell me where I am doing wrong
You are passing $(img) this should be only img inside you $.each.Also you where printing console.log('first',.. instead of this if your image has name attribute use that .
Here is demo code :
var img = $('.data').find('img');
$.each(img, function() {
console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data">
<img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:70px;width:70px">
<img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:40px;width:40px">
<img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/jp-mountain#2x.jpg" style="height:50px;width:50px">
</div>
i was not getting the height and width of an image because the image load event happens very late in the load process
Finally I found an answer
var img = $('.data').find('img');
$.each(img, function() {
$(this).bind('load', function() {
console.log($(this).height);
}
});
it worked for both img and $(img)

How to refresh offsetHeight of div after changing img src on child using pure javascript?

I need to change an image in a div and then immediately centre it on the screen by calculating its height and width and then setting its left and top values. But when I change the img src and then try to get the div's offsetHeight and clientHeight, both the values are wrong. Strangely the offsetWidth and clientWidth values are correct.
Is there a way to refresh the div and get the correct value?
Edit: It appears that changing the image src makes everything after that not work. The change to the onclick event imageObj.onclick = function() {contractImageView(imageId);}; isn't working now either. If I comment out the if statement it all starts working again.
Below is the code...
// Get the page dimensions
var pageBody = document.getElementById(currentBody);
// If you couldn't get the page body, abort.
if (!pageBody) {
return;
}
var pageBodyHeight = window.innerHeight;
var pageBodyWidth = pageBody.offsetWidth;
var imageDiv = document.getElementById(imageId);
var imageObj = imageDiv.children[0];
var paraObj = imageDiv.children[1];
// If you can't get the div or its image, then abort.
if (!imageDiv || !imageObj) {
return;
}
// Check whether the image has been loaded yet, and load if needed
if (imageObj.src.indexOf('lazy_placeholder.gif') !== -1) {
for (item in photoLazyData) {
if (item === imageDiv.parentElement.id) {
imageObj.src = photoLazyData[item][imageDiv.id];
}
}
}
// Change the images class.
imageDiv.className = 'active_design_div';
imageDiv.style.visibility = 'visible';
imageDiv.style.opacity = 1;
// Set the objects new onclick method to collapse the image
imageObj.onclick = function() {contractImageView(imageId);};
// Calculate the right size
imageDiv.style.maxHeight = pageBodyHeight + 'px';
imageDiv.style.maxWidth = pageBodyWidth + 'px';
imageObj.style.maxHeight = pageBodyHeight + 'px';
imageObj.style.maxWidth = pageBodyWidth + 'px';
// Calculate the margins.
var imageDivWidth = imageDiv.offsetWidth || imageDiv.clientWidth;
// ## THIS IS WRONG IF THE ABOVE IF STATEMENT CHANGES THE SRC ##
var imageDivHeight = imageDiv.offsetHeight || imageDiv.clientHeight;
console.log(imageDiv.offsetHeight + ' : ' + imageDiv.clientHeight);
console.log(imageDiv.offsetWidth + ' : ' + imageDiv.clientWidth);
var leftOffset = (pageBodyWidth - imageDivWidth) / 2;
var topOffset = (pageBodyHeight - imageDivHeight) /2;
// Adjust styling to make the div visible and centred.
imageDiv.style.left = String(leftOffset) + 'px';
imageDiv.style.top = String(topOffset) + 'px';
currentId = imageId;
toggleBlackDiv();
Edit: I got this working in the end using Joonas89's answer. I basically moved the if statement that changes the src value to another function that is called prior to the one above. This solved the onclick problem mentioned above. I then changed the divs left/top from calculated values to 50% as detailed by Joonas89 (but on the container div rather than the img element), along with the new transform property. The div and img already had a position value of fixed so didn't need to change that.
Are you sure u want to calculate top and left positions? Wouldent it be better to add a class like this, that always centers it
.parentDiv{
position: relative;
}
.imageElement{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

What is wrong with following javascript code

what is wrong with the following code? I had problem to mix double quotes, with single quotes. so, I defined separate method for onclick. Some how it seems syntax is not right
<table style='border-style:none; cursor:pointer;' onclick="myFunc()" >
function myFunc() {
width1= getWindowDim().width;
height1= getWindowDim().height; opt23='resizable=yes,fullscreen=yes,location=no,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,fullscreen=yes,width='+width1 +',height='+heigh1;
window.open('http://ibm.com','popupwin',opt23);
}
Use jquery for height and width it may work
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
$(window).width(); // returns width of browser viewport
$(document).width(); // returns width of HTML document
Try this, onclick had missing double quote
<table style="border-style:none; cursor:pointer;" onclick="myFunc()" >
function myFunc() {
width1 = getWindowDim().width;
height1 = getWindowDim().height;
opt23 = 'resizable=yes,fullscreen=yes,location=no,toolbar=no,' +
'directories=no,status=no,menubar=no,scrollbars=yes,' +
'fullscreen=yes,width= ' + width1 + ',height=' + heigh1;
window.open('http://ibm.com','popupwin',opt23);
}

Getting dimensions of background-image

I'm trying to get width and height of element's background-image. When you click on it, it should show it inside the element ("200 300" in this case).
HTML:
<div id='test'></div>
CSS:
#test {
width: 100px; height: 100px;
background-image: url(http://placehold.it/200x300);
}
JavaScript:
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function(item) {
var img = new Image(); //Create new image
img.src = item.css('background-image').replace(/url\(|\)$/ig, ''); //Source = clicked element background-image
return img.width + ' ' + img.height; //Return dimensions
};
Here's the Fiddle. The problem is it works only in Chrome, all the other main browsers return "0 0". I have no idea what's the reason. Isn't that graphic fully loaded?
The issue is that some browsers add quotes to the CSS, and it was trying to load (in the fiddle's case) "http://fiddle.jshell.net/_display/%22http://placehold.it/200x300%22". I've updated your .replace() to look for " as well, and a fiddle is at http://jsfiddle.net/4uMEq/
$('#test').on('click', function () {
$(this).text(getDimensions($(this)));
});
var getDimensions = function (item) {
var img = new Image();
img.src = item.css('background-image').replace(/url\(|\)$|"/ig, '');
return img.width + ' ' + img.height;
};
I guess you need to wait for onload event on image.

Categories

Resources