Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control iframe height with jQuery

Tags:

I am using jQuery to control the height of an iframe.

jQuery("iframe",top.document).contents().height();  

This works when the height of the iframe increases. When the height decreases it does not work. It returns the old value only. Why is this happening?

like image 402
Saravanan Avatar asked Jun 01 '09 10:06

Saravanan


2 Answers

It works for me If I set it and retrieve it without using .contents(). Please see my example below.

function changeFrameHeight(newHeight){
  jQuery("iframe",top.document).height(newHeight);
  alert("iframe height=" + jQuery("iframe",top.document).height());
}

EDIT: If I understand correctly, you are trying to get rid of the scroll bars by calling the increment and go back to the original height by calling decrement.

After doing multiple tests across different browsers. Here's the code that works in FF, IE, Chrome, Safari and Opera.

//first declare a variable to store the original IFrame height.
var originalHeight = $("iframe",top.document).height();

Change your heightIncrement function to use the following:

heightIncrement:function(){
 var heightDiv = jQuery("iframe",top.document).contents().find('body').attr('scrollHeight'); 
 jQuery("iframe",top.document).css({height:heightDiv});
}

Change your heightDecrement function to use the following:

heightDecrement:function(){
 jQuery("iframe",top.document).css({height:originalHeight});
}
like image 23
Jose Basilio Avatar answered Sep 21 '22 13:09

Jose Basilio


i use the following and it works perfectly...

$("#frameId").height($("#frameId").contents().find("html").height());

of course just when it's called (no "autoresize")... but it works increasing as decreasing

like image 100
Tom Avatar answered Sep 18 '22 13:09

Tom