jQuery - Get the height of a div with dynamic content - javascript

I'm having an issue with reading the height of a div when I change the content
My scenario is...
I have a customisable design to which the user uploads a photo. When the photo is uploaded, the design preview is reloaded to display the image
What I need to do is read the size of the image and the size of the parent div to see if the image is too large. If it is, I need to make the image draggable so the user can set the position
My code at the moment is this...
function reloadPreview(data) {
$.when(
$.post('/ajax/get_design_preview.php', data, function(response) {
$('#design_previews').html(response.preview);
}, 'json')
).then(initDraggables);
}
function initDraggables() {
$('.image_preview > img').each(function() {
$(this).bind('load', function() {
var img_height = $(this).height(),
div_height = $(this).parent().height(),
overlap_y = img_height - div_height;
console.log('Img Height: ' + img_height);
console.log('Div Height: ' + div_height);
console.log(overlap_y);
})
})
}
I have the same code for the width which works perfectly, but the height doesn't give the correct value
The img_height and the div_height variables always match the height of the image (680px in my current test) but the div has a fixed height with overflow hidden (applied dynamically, 380px in my current test)
I had the same issue with the width but adding the $.when().then() fixed it
I also had to add the $(this).bind('load', function() { to make sure the image was loaded fully before reading its height
I know/assume it's related to the code triggering before the style for the div height is being applied, but I'm not sure how I can tell when this has happened or how to wait for it before triggering my code
Any help would be much appreciated

Related

Make an empty container the same size as a different container with a child image using JS

Incorrect size: Here's what it looks like on load:
Correct size: Here's what it looks like on window resize:
PROJECT LINK Here is a reference link: https://wp.xingapps.win/
Instructions: Hover over "Shop Ejuice" black button in top navigation and you will see red boxes. These red boxes should match the height of the first image but arent.
Story: I have a problem where im trying to reduce the amount of image requests on a page. I have a grid of images. Instead of loading all the images which are all the same height and width I am just going to load the first image and than the other images will be a <div> that matches the first images height and width. I will then apply a CSS Sprite background images to these div's so they appear as normal images. This will reduce the amount of requests on the page by a lot!
Issue: My example code is working when i resize the browser - it will match the height of the source image perfectly. However on initial load the height and width are incorrect. For some reason a bit smaller than it should be. Not fixed until i resize the window. How do i fix this?
The code:
(function($){
/* Match Quad Menu Div Height to one image */
var imgContainer = $('.mad-hat-parent-menu .quadmenu-product-float'),
sourceImg = $('li#menu-item-15959 span.quadmenu-item-content');
function resizeDiv () {
imgContainer.height(sourceImg.width());
imgContainer.width(sourceImg.width());
}
$(window).on("load resize", function() { resizeDiv(); });
})(jQuery);
Note: (i am actually targetting the container of the first image instead of the image itself) Additionally this issue is hard to see if you are on a screen width smaller than 1650px.
Edit: Try to use the resizeDiv() when the user opens/hovers/clicks the menu, like:
Like:
$(".quadmenu-dropdown-toggle").on({
mouseenter: function (e) {
resizeDiv();
},
click: function(){
resizeDiv();
}
});

How to load page only after JavaScript function has finished executing and performed its magic?

Here's the story...
I have an image that is of dimensions 1174px x 660px within a container of dimensions 1174px x 375px. The image's height is cutoff and only 375 pixels worth of the image's height is displayed as I set overflow hidden on the container.
I have created a JavaScript function that takes this image (1174x660) and vertically centers it in its container (1174x 375) so that the center of the image is at the center of the container.
function allFeaturesImagesResize () {
var allFeatures = function () {
var image = $('.all-features article img'),
container = $('.all-features article'),
container_height = container.height(),
image_height = image.height(),
container_center = .5 * container_height,
image_center = .5 * image_height,
center = (image_center - container_center);
image.css('position','relative').css('bottom', center);
}
$(function () {
$(window).resize(function () {
allFeatures();
}).resize();
});
}
I am using a $(document).ready(function() { //... }); wrapper around this function, however, whenever the page loads I can see the function doing its work of moving the image up to the center point. Is there any way to delay the pay load until after this repositioning is complete?
Keep in mind my site is fluid responsive which is why I need to dynamically position the images as I don't know the user's viewport beforehand dimensions (specifically the width).
Use load instead of ready event. $(window).load(function(){ ... your code } will tell that the code should be executed only after all images are loaded. ready event will be fired when the DOM is loaded even if the images are not finished loading
Note that you are selecting multiple images $('.all-features article img'). By doing images.height() it will only get the height of the first found image. The same for the line that select multiple container.
Your code should be translate into "For each image found do" : $('.all-features article img').each (function(){...});

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.

Get Default Height Of Element On Webpage after css height has been applied)

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.

Squash image into window, unless window is bigger than image

Okay, so I've got an image in the body of my webpage.
If the user's window height is less than 800px (the height of the image), the image should be squashed into it (so that the user can see the whole height of the image).
If, on the other hand, the window height is greater than 800px, the image should be vertically centred.
Any tippers?
Thanks.
using jQuery you could do something like:
var win = $(window);
win.load(function() {
var image = $("#img");
if (image.height() > win.height()) {
image.height(win.height());
} else {
// assuming your image is positioned absolute
// you should measure its dimensions and then position it
// depends on the ways it should be centered... in the current window or the whole document?
}
});
win.resize(function() { /* do something */ });
should do the trick to just resize the image to the height of the window if the image is bigger the selector needs to be adapted for your image element of course...
EDIT: added resize callback

Categories

Resources