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.
Related
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.
How do I go about getting what the height of an element on a page would be if it ignored the 'height' css property applied to it?
The site I'm working on is http://www.wncba.co.uk/results and the actual script I've got so far is:
jQuery(document).ready(function($) {
document.origContentHeight = $("#auto-resize").outerHeight(true);
refreshContentSize(); //run initially
$(window).resize(function() { //run whenever window size changes
refreshContentSize();
});
});
function refreshContentSize()
{
var startPos = $("#auto-resize").position();
var topHeight = startPos.top;
var footerHeight = $("#footer").outerHeight(true);
var viewportHeight = $(window).height();
var spaceForContent = viewportHeight - footerHeight - topHeight;
if (spaceForContent <= document.origContentHeight)
{
var newHeight = document.origContentHeight;
}
else
{
var newHeight = spaceForContent;
}
$("#auto-resize").css('height', newHeight);
return;
}
[ http://www.wncba.co.uk/results/javascript/fill-page.js ]
What I'm trying to do is get the main page content to stretch to fill the window so that the green lines always flow all the way down the page and the 'Valid HTML5' and 'Designed By' messages are never above the bottom of the window. I don't want the footer to stick to the bottom. I just want it to stay there instead of moving up the page if there's not enough content to fill above to fill it. It also must adapt itself accordingly if the browser window size changes.
The script I've got so far works but there's a small issue that I want to fix with it. At the moment if the content on the page changes dynamically (resulting in the page becoming longer or shorter) the script won't detect this. The variable document.origContentHeight will remain set as the old height.
Is there a way of detecting the height of an element (e.g. #auto-resize in the example) and whether or not it has changed ignoring the height that has been set for it in css? I would then use this to update the variable document.origContentHeight and re-run the script.
Thanks.
I don't think there is a way to detect when an element size changed except using a plugin,
$(element).resize(function() //only works when element = window
but why don't you call refreshContentSize function on page changes dynamically?
Look at this jsFiddle DEMO, you will understand what I mean.
Or you can use Jquery-resize-plugin.
I've got it working. I had to rethink it a bit. The solution is on the live site.
The one think I'd like to change if possible is the
setInterval('refreshContentSize()', 500); // in case content size changes
Is there a way of detecting that the table row has changed size without chacking every 500ms. I tried (#content).resize(function() but couldn't to get it to work.
On my website, users can upload large images. I display these images like this:
<img id="userImage" src="userImage.ashx?width=740&id=4fc265d4-a83c-4069-8d6d-0fc78ae2840d">
userImage.ashx is a handler that returns image files based on id, so in this example the image for user 4fc265d4-a83c-4069-8d6d-0fc78ae2840d is returned. You can also set other attributes - in this example only width is given. The image is resized so that it is 740px wide.
I set the src of the image in javascript, once the rest of the page has loaded. By doing this I know how wide the image has to be to fill all the available space:
var width = document.getElementById("userImageHolder").getComputedSize().width;
document.getElementById("userImage").src = "flash/userImage.ashx?type=micrositePhoto&id=" + userId + "&width=" + width;
This all works, but the image doesn't load until everything else on the page has loaded. I have a complex solution to a simple problem.
Is there a better way to do this? What is the best way to shrink/stretch images to fill an area that is only known once the page loads?
Figure out what the upper limit is for width and height and generate the image to that size, then use max-width/max-height to allow the browser to auto scale it based on the size of the browser window.
Try to preload your images in a onDOMReady handler, and then insert in an onLoad one. While this can't guarantee the images to be loaded before everything else, they can at least start loading earlier.
Someting like this (using jQuery):
$(document).ready(function(){
var imageArray = [],
imageSrc = [];
//Fill image src array from somewhere
var len = imageSrc.length;
for(var i = 0; i < len; i++){
var img = new Image();
img.src = imageSrc[i];
img.onload = function(){
//Do something with your loaded image
imageArray.push(this);
}
}
});
I've got a web application that loads some content from an external source to the dom via an ajax call, one of the things that comes back is a set of images (different sizes and aspect ratios) to be displayed in an profile photo section. I'd like for each of the images to be resized to fit within a 64px x 64px area and I'd like to maintain aspect ratio. I was able to do this in firefox, chrome, and safari, but I've no luck getting this to work in IE 7 or 8. The problem I've had is finding a jquery event that reliably gets triggered after the image loads since the image was added after the page load. Here's what works in the listed browsers:
$(window).load(function () {
$('.profileThumbnail').each(function (i) {
var divHeight = $(this).height();
var divWidth = $(this).width();
if (divHeight > divWidth) {
$(this).css('height', '64px');
$(this).css('width', 'auto');
}
else {
$(this).css('height', 'auto');
$(this).css('width', '64px');
}
divHeight = $(this).height();
var divParentHeight = $(this).parent().parent().height();
var divNewHeight = (divParentHeight - divHeight) / 2;
$(this).parent().css('top', divNewHeight);
divWidth = $(this).width();
var divParentWidth = $(this).parent().parent().width();
var divNewWidth = (divParentWidth - divWidth) / 2;
$(this).parent().css('left', divNewWidth);
});
});
I'm also trying to center (horizontally and vertically) them which is what the rest of that code does, but I think I've got all of that working if I can find a way to trigger this code after the image loads in IE.
keep in mind this needs to work both on the first visit (not cached) and subsequent visits (cached). I'm looking for a jquery, javascript, or css solution as I want to avoid the roundtrip/bandwidth for each image.
Have you tired to add a load event to the images yourself which triggers when the image is loaded? This is how image preloaders work.
var img = document.createElement("img");
img.onload = function(){ alert('loaded'); }
img.onerror = function(){ alert('error'); }
img.src = "foo.png";
You can add the onload to the image elements themselves if you are not doing the preload approach.
The problem I've had is finding a jquery event that reliably gets triggered after the image loads since the image was added after the page load.
Instead of setting an onload listener for the window, set an onload listener for the images you are loading remotely. Set the listener after you create the image object and before you insert it into the body. The listener can basically be all the stuff insife of the .each() in the code you posted,
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
});