Get the Height of an Image - javascript

This should be easy but it's not. I just need the height of an image:
<div id="map">
<img src="myimage.jpg">
</div>
$("#map img").height(); // returns 0

Use .clientHeight (pure JavaScript):
https://jsfiddle.net/ryanpcmcquen/v6yz8t3u/
console.log(document.querySelector('img').clientHeight);
<img src="//makelin.us/100/100" />
Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
Note that this will give you the height as the image appears on the page, it could be affected by CSS.
Note: To get the actual height of the image, use .naturalHeight.
Great article here: https://davidwalsh.name/get-image-dimensions
To make sure this runs after the image has loaded, do:
window.addEventListener('load', function () {
console.log(document.querySelector('img').clientHeight);
});

The problem is that the height or width are not calculated yet, listen to the loading of the image with .on( "load", handler )
$("#map img").on("load", function(){
var height = $(this).height();
$('#output').html('height=' + height);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="map">
<img src="https://via.placeholder.com/400x40">
</div>
<div id="output"></div>

You can refer following example to get height of image-
<div id="map">
<img id="img_id" src="http://www.clickerzoneuk.co.uk/cz/wp-content/uploads/2010/10/PuppySmall.jpg" >
</div>
write following code in js file
var height = document.getElementById("img_id").clientHeight;
alert(height);
check example using following link-
http://jsfiddle.net/v60mut3L/1/

This worked for me:
$(window).load(function () {
var artLists = [];
$("ul.articles").each(function (index) {
var imageHts = [];
$("li img", $(this)).each(function () {
imageHts.push($(this)[0].height);
})
artLists.push(imageHts);
})
});

Related

Fadein() effect to a function: how to?

I have this function that works well for lazy loading.
panel.find('img[data-src]').each(function(){
element = $(this);
element.attr('src', element.data('src'));
element.removeAttr('data-src');
How can I give a fadeIn() effect to that removeAttr function?
I tried:
element.removeAttr('data-src').fadeIn();
but it doesn't work. The img code looks like this and I simply want the dot.png to fadeOut and the original.jpg to fade in.
<img src="dot.png" data-src="original.jpg">
http://jsfiddle.net/7s1yb1un/6/
Thanks in advance
You cannot fade a src change on an img element. To acheive this you'll need two img elements. The second one will have a the src "original.jpg" and will have a higher z-index and start with display: none for a style. Then you can fade it in and it will fade in over the dot.
EDIT Given your new question, you could do the following:
Add an onload listener for the image
Just before changing the "src", fade the image out
Then change the "src" to "original.jpg"
In your onload function, do a fadeIn
Here is what I have done.
Added a fadeOut(5000), the img with original src will fadeout after 5 sec.
Called a function with timeout of 6sec, which changes the src with data-src and fadeIn(5000) in 5 sec, I hope this solves your problem.
JS code is below
var myVar;
function myFunction() {
myVar = setTimeout(function(){
var src = $("img.hide").attr("data-src");
$("img.hide").attr("src",src);
$("img.hide").fadeIn(5000);
}, 6000);
}
function myStopFunction() {
clearTimeout(myVar);
}
$(document).ready(function() {
$(".hide").fadeOut(5000);
myFunction();
});
The following code would fade out, change the src, then fade in.
JSFiddle
HTML
<div id="fullpage">
<div class="section">
<img class="fadeable" src="http://1.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?size=800" data-src="http://2.gravatar.com/userimage/5/ff5263e8c30557b57e64423ee8496e41?size=800" width=100 height=100 alt="smile"></div>
</div>
JS
$(function() {
$('img[data-src]').each(function(i, e) {
// cache element
original_img = $(e);
original_img
.fadeOut(function(){
original_img.attr('src', original_img.attr('data-src'))
})
.fadeIn();
})
});
Thanks guys. I found this script working (somehow), the images just blink sometimes. I don't know if semantically correct.
$(function() {
$('img').one("load", function() {
var e = $(this);
e.data('src', e.attr('data-src'));
e.animate({"opacity": 0}, 400);
e.data('src');
e.animate({"opacity": 1}, 400);
})
});
The following code would clone the images that have the data-src attribute, then hide the clone, update the clone src, position it over the original image, and fade in. Would this work for you?
JSFiddle
HTML
<div id="fullpage">
<div class="section">
<img class="fadeable" src="http://1.gravatar.com/avatar/767fc9c115a1b989744c755db47feb60?size=800" data-src="http://2.gravatar.com/userimage/5/ff5263e8c30557b57e64423ee8496e41?size=800" width=100 height=100 alt="smile"></div>
</div>
JS
$(function() {
$('img[data-src]').each(function(i, e) {
// cache element
original_img = $(e);
// get position of original image
offset_left = original_img.offset().left;
offset_top = original_img.offset().top;
// get data-src of
data_src = original_img.attr('data-src');
// clone original image
original_img.clone()
.hide()
// put it directly in the body, so it can be positioned
.appendTo('body')
// set the new src
.attr('src', data_src)
// place it over the original image
.css({
"left": offset_left,
"top": offset_top,
"position": "absolute"
})
.fadeIn(function(){
original_img.attr('src', data_src);
$(this).remove();
});
})
});

Setting margin-top of one element to the height of another element using JQuery

I'm trying to have a header at the top with a non-fixed height but a fixed position, and below that a content area. Now, I simply added a fixed padding-top to the element so the content would show below the header. I'm trying to do this using JavaScript and JQuery. I think the way I did it would be the best way, but it doesn't quite work.
[HTML]
<div class="contentPage" id="page_1" name="templates">
<div class="contentPageHeader">
<a href="#menu">
<div class="pageBack">
<h4>Back</h4>
</div>
</a>
<h3>Templates</h3>
</div>
<div class="contentPageContent">
</div>
</div>
[JS]
var headerHeight = $('.contentPageHeader').css( 'height' );
$('contentPageHeader').css('margin-top', headerHeight);
For a full demo visit this JSfiddle
You should to fix your javascript:
var headerHeight = $('.contentPageHeader').outerHeight();
$('.contentPageContent').css('margin-top', headerHeight);
Also this code should be placed inside the click method.
jsfiddle
You need to define the unit for marginTop for eg. px or %:
$('.contentPageHeader').css('margin-top', headerHeight + 'px');
//^^ missed a selector (the dot)
Try this
$(document).ready(function () {
$("a").click(function () {
if (this.hash) {
var hash = this.hash.substr(1);
var $toElement = $("div[name=" + hash + "]");
if (hash == "menu") {
$('.contentPage').fadeOut(300);
$($toElement).fadeIn(300);
} else {
$('#menu_holder').fadeOut(300);
$($toElement).fadeIn(300);
}
}
var headerHeight = $('.contentPageHeader').css( 'height' ); //your code added here
$('.contentPageHeader').css('margin-top', headerHeight);
});
});
Fiddle:https://jsfiddle.net/mdeujc0u/3/
Updated fiddle: https://jsfiddle.net/mdeujc0u/5/

Javascript. Can't get element style

I'm trying to get width & height of the img element. It gives 0px whatever I do.
function foo(element){
if(element){
var el=document.querySelector(element);
var img=el.getElementsByTagName("img")[0];
alert(img.style.width);
}
}
foo();
And the html:
<div id="theid" class="theclass">
<img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>
<script>
foo("#theid");
</script>
I've also tried .offsetWidth, .clientWidth and defaultView.getComputedStyle(img,"");
How about this
function foo(imgId){
var img=document.getElementById(imgId);
alert(img.offsetWidth);
}
foo('img');
Use .naturalWidth & .naturalHeight to get the actual size of image
function foo(element){
if(element){
var el=document.querySelector(element);
var img=el.getElementsByTagName("img")[0];
alert(img.naturalWidth );
}
}
foo("#theid");
DEMO
Image height/width is always returned 0px unless defined in CSS.
Try this piece of code, but you are loading the image again in this case (could be cached, but still).
var image = new Image();
// replace with appropriate library method
image.addEventListener("load", function() {
//get image height/width here
}, false);
image.src = el.getElementsByTagName("img")[0].src;
You need to use the element offsetWidth
Here is a working fiddle and the code:
function foo(element) {
if (element) {
var el = document.getElementById(element);
alert(el.offsetWidth);
}
}
foo("theid");
Note that I have used the document.getElementById only as that will get the element. No need to have getElementsByTagName in this case. And do not prefix the id with a '#' as that notation is of jquery not javascript.
<div id="theid" class="theclass">
<img id="img" alt="img" name="the img" src="img/img.jpg" />
</div>
<script>
foo("#theimg");
</script>
You are calling foo() by passing #theimg which is not present in document, call by passing #img , i.e. like this
<script>
foo("#img");
</script>
if you use above img id, remove var img=el.getElementsByTagName("img")[0]; in your function, we can directly access it.Okay
<script>
foo("#theid");
</script>
use this to keep your function as it is. Okay
It'll give 0px, if the image failed to load otherwise it'll give the width and height of the actual image, And if you want to access the attributes like left, right, top, bottom for these attributes we need to set image position to absolute then we can access.

jquery, click to enlarge image, then click agian make it go back to previous width

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<img src="https://i0.wp.com/www.thekitchenwhisperer.net/wp-content/uploads/2014/04/BelgianWaffles8.jpg" width="100" class="image" />
<script>
$(document).ready(function() {
$('.image').click(function() {
$(this).css('width', '100%'); // original width is 500px
});
});
</script>
How do add some codes so that i click it again, it goes back to the previous width(100px)?
Like this?
$(document).ready(function(){
$('.image').click(function(){
$(this).css('width', function(_ , cur){
return cur === '100px' ? '100%' : '100px'
});
});
});
Fiddle
First of all I would replace the width attribute for your img with CSS. Next up you can just remove the assigned inline-css (which is what jQuery adds) by calling
$(this).css('width', '');

Background-Image fade jquery

I have a div and I want to fade in and out of 5 different background images at random.
I have downloaded a jquery plugin for this, but unfortunately it alternates - I'll explain.
You must set a default background image (for this case lets say "image1") and then load an array of images (say image2, image3, image4, and image5). What the plugin does is duplicate the div and place it directly over the original one, then fades in and then out one of the array of images. The undesirable effect that I'm getting from this is:
1,2,1,3,1,4,1,5
as opposed to:
1,2,3,4,5
Because the fade out simple reveals the default image once again.
Without re-inventing the wheel is there a way to modify the code to that when the fade-in animation is complete (the default is completely concealed) I swap out the image on the background div so that when the fade out begins there's a new image below? I'm relatively new to JQuery and so this is not my strength.
Heres the action part of the plugin:
var tempImage = new Image();
jQuery(tempImage).load( function(){
var newImage = ( helperElement.css('display') == 'block' ) ? jQuery(this) : jQuery(helperElement);
newImage.css('backgroundImage', 'url('+tempImage.src+')');
helperElement.animate( settings.effect, settings.duration, settings.easing, settings.callback );
});
tempImage.src = src;
And in my HTML:
<script>
document.getElementById('content_container_home').style.backgroundImage = "url('img/buttons.jpg')";
$( function(){
var bgImages = [ 'barker.jpg', 'boards.jpg', 'feet.jpg', 'glasses.jpg' ];
var currImage = 'buttons.jpg';
setInterval( function(){
do{
var randImage = bgImages[Math.ceil(Math.random()*(bgImages.length-1))];
}while( randImage == currImage )
currImage = randImage;
$('#content_container_home').BgImageTransition( 'img/'+currImage );
}, 5000)
});
</script>
Check out my answer to another question
This should do the trick:
HTML:
<div id="testers">
<div class="tester">
<img src="http://regmedia.co.uk/2008/03/18/google_adwords_machine.png" alt="" />
</div>
</div>
<div id="morework">
<div class="holderdiv">
<div class="tester">
<img src="http://www.swwebs.co.uk/images/google-pagerank.jpg" alt="" />
</div>
</div>
<div class="holderdiv">
<div class="tester">
<img src="http://jsfiddle.net/favicon.gif" alt="" />
</div>
</div>
</div>
CSS:
#morework{display:none;}
jQuery:
$(document).ready(function(){
function runIt(){
$('#morework').find('.holderdiv').each(function(i, elem) {
$("#testers").delay(5000).fadeOut(1000, function() {
$(this).html($(elem).html());
}).fadeIn(1000, runIt);
});
};
runIt()
});
Check it out in action here - http://jsfiddle.net/sfsPx/

Categories