how to get the height and width of image in javascript? - 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)

Related

How can I get the size of images by 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?

Change background url of div via HTML tag

I have a div (CSS - height: 250px, width: 70%) and I have set a background via CSS. I want to change the background onhover.
That's simple, I know. But I want to get sources of backgrounds from the HTML tag.
Ex.:
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
Can anyone help me please?
If you're not using jQuery you can achieve the desired effect using basic Event Listeners. https://jsfiddle.net/gnu9utos/3/
// first get the element that we'll be interacting with
var element = document.querySelector('.somediv');
// assuming we managed to successfully get the element from the document
if(element) {
var before = element.getAttribute('data-imgbefore');
var after = element.getAttribute('data-imgafter');
if(before && after) {
element.style.background = 'url(' + before + ')'; // set the initital state
element.addEventListener('mouseover', function(event) {
element.style.background = 'url(' + after + ')';
});
element.addEventListener('mouseout', function(event) {
element.style.background = 'url(' + before + ')';
});
}
}
You might want to add a check for mouseleave to revert the image back to it's original state and add a little bit of css.
I hope this was helpful.
you can do this with this simple JQ
maybe it's not the best solution but it works.i added background-color so you can see the change. but you can remove that and leave only background-image
see here
jsfiddle
made 2 variables and assigned them to each image ( before and after img ) to each div with class .somediv
add an initial background-image to the div
then at hover, the background-image of the div changes between imgbefore and imgafter
jq :
$(".somediv").each(function(){
var imgbef = $(this).data("imgbefore"),
imgaft = $(this).data("imgafter")
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
$(this).hover(function(){
$(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
}, function(){
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
});
});
HTML :
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
CSS :
.somediv {
height:250px;
width:70%;
}
let me know if it helps
You can easily achieve that with javascript. You can also add an onmouseleave function, but this time, passing this.dataset.imgbefore as second argument.
changebg = function(el, i) {
var t = "url("+i+")";
el.style.backgroundImage = t;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="somediv" id="mydiv" data-imgbefore="http://lorempixel.com/400/200/sports" data-imgafter="http://lorempixel.com/400/200/animals" onmouseover="changebg(this, this.dataset.imgafter)">Lorem</div>
</body>
</html>
You can add all the div that you like and change only the data-imgbefore and data-imgafter !!!
$(document).ready(function(){
$('.somediv').each(function( index, value ) {
var img = $(this).attr('data-imgbefore');
$('.somediv').css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
});
//$('.somedive').css({'background-image':'url("http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png")', 'background-size':'200px 200px'});
$('.somediv').hover(
function () {
var img = $(this).attr('data-imgafter');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
},
function () {
var img = $(this).attr('data-imgbefore');
$(this).css({'background-image':'url('+ img +')', 'background-size':'200px 200px'});
}
);
});
.somediv {width:200px;height:200px;border:1px solid #F2F2F2;border-radius:4px;display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
<div class="somediv" data-imgbefore="http://www.palladio-tv.it/Internet/siti_gec/2B/Manzan_Disney/codice/Pippo.png" data-imgafter="http://www.filastrocche.it/contenuti/wp-content/uploads/2001/04/pippogoofy_352.jpg"></div>
Cheers!!!
Not sure if I understand what you are trying to accomplish. Why don't you abandon the HTML tag requirement and just try css :hover?
#somediv {
background: url(...);
}
#somediv:hover {
background: url(...); /* different url */
}
http://www.w3schools.com/cssref/css3_pr_background.asp

Assign an image as a css background image

I'm working on a responsive slider, it's not that easy. Basically it must works from 320px to 1920px, with a fixed height.
So its giving me a headache, I have an easy fix : instead of using the a > image, I will assign the image url as background image for the a, then set the image opacity to 0. So, I will be able to use the cover+center background properties and my slider will be perfect.
But I have problems doing that because I'm unsure how to do it, I spent time yesterday but couldn't assign the image as background.
Here is what the markup looks like (I removed unecessary blocks, just keeping the most importants)
<div class="slide-image">
<a href="xyz.com">
<img src="image.com/img.jpg">
</a>
</div>
<div class="slide-image">
<a href="zxy.com">
<img src="image.com/img2.jpg">
</a>
</div>
etc ..
I tried that code which doesnt work, the variable gets a value but nothing is assigned :
$(function() {
if ($('.slider').length) {
$('.slider').slick({});
$('.slide-image').each(function() {
var img = $('img', this).attr('src');
$('a', this).css('background-image', 'url(' + img + ')url');
};
}
});
You're trying to read "src" attribute, but you've set "url" in your HTML. Change your JS:
var img = $('img', this).attr('url');
Also you're assigning wrong style. It should be:
$('a', this).css('background-image', 'url(' + img + ')');
Note you have an error in this line:
$('a', this).css('background-image', 'url(' + img + ')url');
------------------------------^
It must be
$('a', this).css('background-image', 'url(' + img + ')');
And <img> tag is bad,
<img url=""> BAD
<img src=""> GOOD

fadeOut then fadeIn sequentially

I'm trying to fade out one image, then fade in another image in the same spot.
So far I've got this fiddle, but you can see it changes the image before the .fadeOut() function finishes, when changing image via clicking thumbs. I've read that jQuery doesn't run sequentially as standard (which my code is assuming it does), so I tried adding in the completed function, like so:
$('#image').fadeOut('fast', function() {
$('#image').html('<img src="' + image + '" class="image"/>');
$('#image').fadeIn('fast');
});
However my issue is still present. What should I do to fix this?
I wouldn't destroy and recreate the elements; I'd just update the attributes. I'd also include a .stop(true, true) to cancel any previous animation and jump straight to the end before starting the fadeout, in case someone clicks quickly.
var images = [
'http://i.stack.imgur.com/uClcV.jpg?s=328&g=1',
'https://www.gravatar.com/avatar/d050da3cf82fdf6cfa431358fee9a397?s=128&d=identicon&r=PG&f=1',
'https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=128&d=identicon&r=PG'
];
var current = 0;
updateImage(images[current], images[current]);
function updateImage(image, title) {
var img = $('#image');
img.stop(true, true).fadeOut('fast', function() {
img.find('a').attr('href', image).attr('title', title);
img.find('img').attr('src', image);
img.fadeIn('fast');
});
}
$("#next").click(function() {
current = (current + 1) % images.length;
updateImage(images[current], images[current]);
});
<input type="button" id="next" value="Next">
<div id="image">
<a>
<img style="height: 128px; width: 128px"><!-- Never do that, but for a demo, it's okay -->
</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is expected result that #slider not fade to appearance of empty
background during image transitions ?
Fades to either white, ready for the new image to fade in, or a crossfade - either would be acceptable
Try setting #slider width , height to expected img width, height; setting background-color to #000
css
#slider {
width:500px;
height:505px;
background-color:#000;
}
js
//clicking thumbnails
$(".image").click(function () {
var image = $(this).attr("rel"); //getting the rel tag from the a tag
var title = $(this).attr("data-title"); //data title from a tag
$('#image').fadeOut('fast', function() { //fades out last image
$('#image').html('<a href="' + image + '" data-lightbox="image-1" data-title="' + title + '">'
+ '<img src="' + image + '" class="image"/></a>')
.fadeIn('fast');
})
jsfiddle http://jsfiddle.net/bmu43fm7/13/

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