width() not returning a value - javascript

I have an image in a page that I am trying to get the width of.
<img class="zoomerIcon" src="zoomer.png" />
So I'm trying to get the width like this.
var imageWidth = $('.zoomerIcon').width();
However the value is 0 unless I set the width property in the tag.
Does width() only return a width greater than 0 if it's manually set in the property? You can see the whole script here.
http://www.wantedcreative.com/development/zoomer/index.html
Thanks

Update
Sorry, I should have looked at your source first. Here is how you need to change your code. The important thing to realize, is you can't get the width until the image has fully loaded. That is why I use a load event callback to retrieve the widths:
// Create the img element, add a load handler, then append it to the body
var $img = $('<img class="zoomIcon" alt="zoom icon" />').load(function(e){
// get icon image properties for use with animation
var imageWidth = $(this).width();
var imageHeight = $(this).height();
// ... any code that uses these variables needs to go in here ...
}).attr('src', zoomImage).appendTo( document.body );
Original Answer: This is general information.
You are probably putting this code in document.ready which will try to retrieve the width before the image has loaded. Try this instead:
$(window).load(function(){
var imageWidth = $(".zoomer").width();
alert( imageWidth ); // Should be correct
});

Related

img.height() and img.width() returning 0 in chrome,but returns correct value in mozilla

I have an image field in my markup.I am setting its source using jquery. I need its height and width. for that I have used image.height() and image.width() methods. it works proper in mozilla but not in chrome, I have tried image.height and image.width method, but not getting any value. also I have tried by changing prop method to attr for setting the image src, but it is also gives me the same result. I am pasting my code here.
html
<div>
<img src class="my-image"/>
</div>
Jquery
$(document).ready(function(){
var img = $(".my-image");
imageWidth = $('.my-image').width();
imageHeight = $('my-image').height();
alert(imageHeight);
});
what is the error here ? any help is appreciated
What happens is the image is not yet loaded on $(document).ready(); and at that point the element has dimensions of 0px by 0px. In order to ensure your image is loaded use the $(window).load(); event instead of document ready.
$(window).on("load", function(){
var img = $(".my-image"),
imageWidth = $('.product-image-og-size').width(),
imageHeight = $('img.product-image-og-size').height();
alert(imageHeight);
});

On window resize get new width and last one

I`m trying build function who on document width changes get current webpage windows size and save last of past width with function, so i need past value.
So in pseido code it will be:
on resize(function){
var CURENT_W = 100
**var PAST_W = 90**
var MODIFIER = CURENT_W - PAST_W
jQuert('#element').css('atribute': MODIFIER)
});
So i need function who tell me how much window is resized.
How to get old document width? It`s possile?
Maybe there is some better method?
I've made a little snippet for you, you can use it as you want, just try to understand the script.
I'm 100% it can be done in some easier way, but this is the first that came to my mind
$(document).ready(function() {
// store a variable with body's width
var initial = $("body").width();
// render the body's width value on the selector
$("#initialwidth, #actualwidth").text(initial);
//now let's resize
$(window).resize(function() {
// Before doing some maths, let's get the width from #actualwidth span instead of directly from the variable
// the span has the value "static" because it was defined outside the ".resize()" event
var staticWidth = $("#initialwidth").text();
var newWidth = $("body").width();
//new width - initial width = difference
var finalWidth = newWidth - staticWidth + "px";
$("#actualwidth").text(newWidth);
$("#diff").text(finalWidth);
});
});
Here's a jsfiddle:
http://jsfiddle.net/2dcsonjg/

How to get the height of an image in javascript

Let's say the original height of an image is 200px or lower than 100px. Then I set the 'max-height: 100px' of an image. How would I get its displayed height. I've tried $('img').height(). But is it just returning me a 0 value.
Use window.getComputedStyle ( Firefox, Opera, Safari ) :
example :
<img style="height:100px;max-height:100px;" src="img.gif" id="test">
var img = document.getElementById('test');
var height = window.getComputedStyle(img).height;
console.log(height)
will output 100px
For IE you can use
var height = img.currentStyle.height;
Use simple JavaScript:
var img = document.getElementById('imageid'); // use the id of your image
var height = img.clientHeight;
You need $('img').innerHeight() - Get the current computed height for the first element in the set of matched elements, including padding but not border.
http://api.jquery.com/innerHeight/
$(document).ready(function() {
$("img").load(function() {
alert($(this).height()); // for height
alert($(this).width()); // for width
});
});
Make sure you have jQuery initialized ABOVE this script, as in this case it seems you are trying to use jQuery by the " $ " command.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
Put the above code in the head of the document.
in the body, but the image
<body>
<img src="img.jpg" id="new-image" />
</body>
Above is the HTML, the image has an ID of "new-image"
IDs can be selected using jQuery by adding a # before the ID
e.g. "#new-image"
$(document).ready(function(){
// Retrieves computed image height and stores to variable "imgHeight"
var imgHeight = $('#new-image').height();
// Shows current computed/displayed height in development console
console.log(imgHeight);
// If you don't know how to access the development console
// You can also use alert (but you should learn to use the console!)
alert(imgHeight);
}
Make sure to wrap the above code in a script tag.

How can I get the width and height of a dynamically added image?

I have a problem with geting the real width and height of some img tags which are added dynamically. Here is my code:
var imgcont = $("<img src='' /> ");
imgcont.css("display","none").appendTo("body");`
$("div#lightbox ul").on("click","li", function(){
var source = $(this).children("img").attr("src");
console.log(imgcont.attr("src",source).width());
})`
If I click for the the first time I get the correct values for width and height but if I click a second time I get the values of the previous clicked element. In order to get the correct values I have to click again on the same element.
How can I get the correct values for img width and height on the first click?
$("div#lightbox ul").on("click", "li", function() {
var source = $(this).children("img").attr("src");
imgcont.attr("src", source).load(function() { // after load finish
// get width
console.log( this.width ); // according to #Alnitak comment
});
})
You have to wait until the image has loaded before you can access its dimensions.
Catch the image's onload event to handle that.
imgcont.on('load', function() {
console.alert(this.width);
});
Note the use of this.width if you want to get the actual width property of the image, and not its on-screen dimensions. They may not be the same.

Javascript - Image change an resize to full background

As a quick explanation, I created an image that resizes to fill the background using this function which works great:
function resize_bg(element_id){
$("#"+element_id).css("left","0");
var doc_width = $(window).width();
var doc_height = $(window).height();
var image_width = $("#"+element_id).width();
var image_height = $("#"+element_id).height();
var image_ratio = image_width/image_height;
var new_width = doc_width;
var new_height = Math.round(new_width/image_ratio);
if(new_height<doc_height){
new_height = doc_height;
new_width = Math.round(new_height*image_ratio);
var width_offset = Math.round((new_width-doc_width)/2);
$("#"+element_id).css("left","-"+width_offset+"px");
}
$("#"+element_id).width(new_width);
$("#"+element_id).height(new_height);
return true;
}
So no problem for the full background image. The problem appears, when I change the image source using Javascript. In other words, I have 1 image set as background but on hover of certain elements on the page, the image changes but it doesn't change the resize right. So the first image on load is resized and positioned correctly, but when I switch the image using .attr('src',newimg) the image is not resized correctly even though I call the function again.
Here is the code I use to change the image and resize it:
$('#menu_work li a').hover(function(){
$('#content').hide();
var img_src = $(this).next('img').attr('src');
$('#full_screen_img').attr('src', img_src );
resize_bg();
$('#full_screen_img').show();
},function(){
$('#full_screen_img').hide();
$('#content').show();
});
Thanks for any help.
It appears that you have left out the element_id argument when calling resize_bg() in the hover event handler. As a result, resize_bg() can't find the element you want to resize.
#maxedison is right, you forgot to pass the element id.
Another problem is that when you change the src, the new image might not be loaded yet, so you won't get the right dimensions in resize_bg until it is.
In that case you'll need to resize the image once it's loaded:
$('#full_screen_img').attr('src', img_src ).load(function() {
resize_bg('<ELEMENT_ID>');
});
resize_bg('<ELEMENT_ID>');
On another note, I'd recommend you change resize_bg to get a jQuery object instead of an id, or even write a plugin ($.fn.resize_bg) if it's a functionality you want to use often.

Categories

Resources