jQuery change size of iframe - javascript

I have a function that change the size of the iframe every time a new content is loading.
It works fine, but there is a little problem:
If I open a big content the size change to it correct hight. If I load after that a smaller content, the height stays the same(from the big content), it isn't getting shorter.
I don't know why, how can I fix it?
$("#mainframe").load( function () {
var c = (this.contentWindow || this.contentDocument);
if (c.document) d = c.document;
var ih = $(d).outerHeight() + 10;
var iw = $(d).outerWidth();
$(this).css({
height: ih,
width: iw
});
});

Related

Loading image delayed display after loaded

So I have this html / css / jQuery / js code that toghether shows a VERY large image in width. The base element should be invisible untill the image is loaded and set. Then the base element is made visible by a small fade.
However the behaviour is a little different.
Once the image is being loaded i can see the small text fading in and it takes a few seconds before then the image just pops up in once (not loading style like from top to bottom appearing)
This is the simplified code i use:
<script>
$(function() {
$("#base").hide();
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').fadeIn(500);
};
img.src = backLayerSRC;
});
</script>
<style>
#base {
position:absolute;
left:0px;
height:100%;
}
#base #img {
position:absolute;
left:0px;
top:0px;
}
</style>
<div id='base'>
some tekst
<img src='' id='img' data-src='path_to_very_large/image.png' />
</div>
Now, how could it be that it just doesn't fade in WITH the image?
Here is an example WITH the image, please check so it becomse clear what i mean
http://jsfiddle.net/uz8mvtap/3
It might depend on the time the browser needs to render the image after the script loaded it.
I played a little with your fiddle and came up with this:
$(function() {
$("#base").css({opacity: 0});
var baseHeight = $(window).height();
var backLayerSRC = $('#img').attr('data-src');
$('#base').height(baseHeight);
var img = new Image();
var imgWidth, imgHeight;
img.onload = function() {
imgHeight = this.height;
imgWidth = this.width;
var factor = 1 * baseHeight / imgHeight;
totalWidth = Math.round(factor * imgWidth);
currentWidth = totalWidth;
$('#base').width(totalWidth);
$('#img').attr('src', backLayerSRC);
$('#img').height(baseHeight);
$('#base').delay(1000).animate({opacity: 1.0},500);
};
img.src = backLayerSRC;
});
Basically using opacity for such a purpose is better because #base continues to occupy the same space, not disrupting the page. And the delay is for the browser, I figured for a big image it takes time to render, so let's give it it.
You could do that.
$('<img />').load( function(){
console.log('loaded');
}).attr('src', imgUrl);
After it loads, it summons a callback, use that callback to do custom function. Let me know how it goes.
or, by the way. You could enter image width and image height into custom var, and compare them on the load, once it reaches your wanted width and height, fade it in.
You seem to be slightly misinterpreting the timeline of your code:
Page loads, (text is visible on screen)
jQuery kicks in, hides #base (text is not visible on screen)
jQuery fades in #base (text is visible on screen again)
This is why you are briefly seeing the text before the image loads - because it is not initially hidden.
Add:
display: none;
To your #base style, add keep the rest of your code the same.
Also I've created an alternative JavaScript solution after you have added the above CSS:
$(function() {
const base = $("#base"),
img = $("#img"),
backLayerSRC = img.attr('data-src'),
baseHeight = $('#base').height();
img.attr('src', backLayerSRC);
img.one("load", () => {
img.height(baseHeight).promise().done(() => { base.fadeIn(2500); });
});
});
Here is the working example of your code I have created:
https://codebrace.com/editor/b16cabfee
Your baseHeight variable is undefined.
May be you should change
$('#base').height(baseHeight);
to
var baseHeight = $('#base').height();
Update:
I have updated the solution. I this solution I have wrapped div around both the text and image. Div wrapped around image is set to position:relative; to keep the image(set to absolute position) from covering the text.
https://codebrace.com/editor/b16f33afb

jQuery not firing on load/ready when server responce is slow

I fire a function on jQuery(document).ready() and on jQuery(window).load(). Both the same function. It is supposed to fire an image resize script.
However, sometimes, when the server is slow to respond, the script doesn't fire at all when the page is done loading.
I've been having this problem for quite a while now, and, maybe it's overkill, but by now, I call the function as shown below, in both the document ready and the window load:
jQuery('img', '.background').each(function(){
jQuery(this).load(function(){
jQuery(this).resizeImage();
});
});
The function it calls is:
jQuery.fn.resizeImage = function() {
console.log('fired');
var bgImg = jQuery(this);
/* get img sizes */
var imgwidth = bgImg.width();
var imgheight = bgImg.height();
/* get window sizes */
var winwidth = jQuery(window).width();
var winheight = jQuery(window).height();
/* get the ratio, checks wether window is bigger or smaller than the image */
var widthratio = winwidth / imgwidth;
var heightratio = winheight / imgheight;
/* checks the difference */
var widthdiff = heightratio * imgwidth;
var heightdiff = widthratio * imgheight;
/* if you want the entire image to always fit the screen, change the > to < */
if(heightdiff>winheight) {
bgImg.css({
width: winwidth+'px',
height: heightdiff+'px',
marginLeft: '-'+winwidth/2+'px'
});
} else {
bgImg.css({
width: widthdiff+'px',
height: winheight+'px',
marginLeft: '-'+widthdiff/2+'px'
});
}
};
Using the console.log, I found that the function doesn't fire at all.
Can anyone point me in the right direction as to why this might not work?
Guess you're miss using the this
jQuery('img', '.background').each(function(){
var $self = $(this);
$self.load(function(){
$self.resizeImage();
});
});
Solved it myself.
The issue was in the following:
jQuery(window).load(function(){
jQuery('img', '.background').each(function(){
jQuery(this).load(function(){
jQuery(this).resizeImage();
});
});
});
Due to the double load (jQuery(window).load and jQuery(this).load) the code didn't execute at all. Since when the window is loaded, the images are already loaded as well.

PhantomJS: getting the rendered dimensions of a page

When using PhantomJS for screen capture where most of a page's content is getting added on or during load via JavaScript, I run into a problem. Calling render() produces the correct image, showing the full content of the page, but evaluating document.body.clientHeight returns a tiny value that is presumably the page's height before any content gets added.
How can I get the height/width of the image as PhantomJS is rendering it? I don't think it's a timing issue, I've tried swapping the order of things or setting long delays to ensure everything is totally loaded.
var wp = require('webpage');
var page = wp.create();
page.viewportSize = { width: 1024, height: 768};
page.open(url, function (status) {
if (status === 'success') {
var f = "rendered.png";
//Produces an image with height 4073px
page.render(f);
//height is only 150
var height = page.evaluate(function() { return document.body.offsetHeight }),
width = page.evaluate(function() { return document.body.offsetWidth });
console.log(height,width);
}
});
Try using the page.onLoadFinished callback:
var wp = require('webpage');
var page = wp.create();
page.viewportSize = { width: 1024, height: 768};
page.open(url);
page.onLoadFinished = function() {
var f = "rendered.png";
//Produces an image with height 4073px
page.render(f);
//height is only 150
var height = page.evaluate(function() { return document.body.offsetHeight }),
width = page.evaluate(function() { return document.body.offsetWidth });
console.log(height,width);
};
This should return the correct height and width after the page content has finished loading. I think the difference is that page.onLoadFinished waits for all content to finish loading and not just for a 200 OK response which is equivalent to the success status.

How can I change an image with another keeping aspect ratio?

I have the following HTML code:
<img id="Card00" src="images/words/back.png" onclick="imageClicked(0,0);">
And the following Javascript code:
function ShowImage(id, row, column)
{
var imagePath = 'images/words/' + id + '.png';
var imgId = '#Card' + row + '' + column;
$(imgId).attr('src', imagePath);
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
if (width > height)
$(imgId).attr('width', 200);
else
$(imgId).attr('height', 200);
}
imageClicked only calls ShowImage.
Back.png is 200x200. I want to change back.png image with another one. That another one (id + .png), is bigger than 200x200, so I need to resize it on ShowImage function.
But I can't do that, because I can't get its new width and height in this piece of code:
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
My goal is to change back.png image with another one, keeping aspect radio.
And there is another problem: first I see the bigger image, and then, sometimes, it gets 200x200. I said sometimes because sometimes I get its width or its height.
Any advice?
The best thing to do is just load the image into memory first, then once it loads get its real height and width, use that info -- URL, height and width -- to determine the appropriate dimensions. Note that this isn't foolproof, though, as caching can mess it up.
Note that you can generalize the below to include maximum dimensions in the function itself, but I think it's pretty easily adaptable:
// Example: replaceImage($("img#someID"), "http://example.com/logo.png");
var MAX_HEIGHT = 80;
var MAX_WIDTH = 80;
function keepAspectRatio(temp, $target, url) {
// Get height and width once loaded
var realHeight = temp.height;
var realWidth = temp.width;
// Get how much to divide by (1 if image fits in dimensions)
// Get rid of ", 1" if you just want everything to be either
// MAX_HEIGHT tall or MAX_WIDTH wide
var factor = Math.max(realHeight/MAX_HEIGHT, realWidth/MAX_WIDTH, 1);
realHeight /= factor;
realWidth /= factor;
// Set the target image's source, height and width
$target.attr("src", url).css({height: realHeight, width: realWidth});
}
function replaceImage($target, url) {
$("<img>").load(function() {
keepAspectRatio(this, $target, url);
}).attr("src", url);
}
jsFiddle Example
EDIT
Swapped places of attr and load per the comment below. I'm not going to go too crazy with optimization beyond that, as what we'd really do if we wanted things perfect would be to preload everything, get its real dimensions, and use that information each time we change the original image.
Did you try:
var width = $(imgId).clientWidth;
var height = $(imgId).clientHeight;

Javascript: Adjusting image container height to dynamic image height after image load?

i load graphs via the following javascript function:
function loadMCorCBGraph(self,surveyID,questionID,varID) {
var img = new Image();
img.onload = function() {
$(self).parents().parents().siblings(".graph_container")
.empty().append(img);
};
img.src = 'drawGraph.php?type=surveys_report_MC_or_CB&surveyID=' + surveyID + '&questionID=' + questionID +
(varID != null ? '&varID=' + varID : '') + '&companyID=<?php echo $_SESSION['companyID'] ?>';
}
however, the graph height is unknown until it is drawn. i was wondering if there was a way to get this height after it has loaded and set the container height to cet height.
i thought about putting:
.css("height", THE_IMAGE_HEIGHT)
in the onload function, but i am having trouble finding this image's height. debugging shows that (inside the onload):
$(this).height() = 0
img.height = ReferenceError: img is not defined
this.height = 425
now the last one, this.height, is clearly referring to the container, which is set with a height of 425px.
any ideas as to how to get the height?
thanks!
img.onload = function() {
$Container = $(self).parents().parents().siblings(".graph_container");
$Container.empty().append(img);
this.find('img').each(function(){
//Dynamically check each image
if(this.height > 400)
{
$(this).height(400);
}
console.log(this); //Should see object with attribs.
})
};
Give that a go and tell me what happens, also check your console log to see if the Object is the image element.

Categories