antivinegar
antivinegar

Reputation: 447

Adapt 100 percent height to javascript widget

I've searched up and down and i've been unable to find an answer that allows me to adapt the height of a page using the code below:

// Set path to the iframe file
var filePath = 'http://www.mysite.com/widget/widget.php';
// Setup the iframe target
var iframe='<iframe id="frame" name="widget" src ="http://www.mysite.com/widget/widget.php" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>';
// Write the iframe to the page
document.write(iframe);

var myIframe = parent.document.getElementById("frame");
// Setup the width and height
myIframe.height = 450;
myIframe.width = 255;

myIframe.src = filePath;
// set the style of the iframe
myIframe.style.border = "1px solid #dddddd";
myIframe.style.padding = "2px";

Notice the "myIframe.height = 450;" that restricts my widget to 450 pixels high... I need it to allow my widget to resize to 100% and yes I tried "100%" and it won't work.

The above code is pulled when I place this code onto a site which creates a simple widget.

< script language="JavaScript" src="http://www.mysite.com/widget/js/javascript-iframe.js" >< /script >

Here is where the original javascript iframe widget came from: http://papermashup.com/creating-an-iframe-with-javascript/ but they don't have instructions on how to have a 100% height

Upvotes: 2

Views: 517

Answers (1)

Alessandro Gabrielli
Alessandro Gabrielli

Reputation: 892

This works for me. The trick is to get the height of the visibile area of the page, not just the height: this because the body height follows the content inside itself, if you have a fixed element height, the body height won't ever be smaller but bigger

$(window).resize(function () {
    //frame height
    var f = $('#frame').height();
    //window visible height <-- height css(height) and other works for the real height, not just the visible
    var h = window.innerHeight; 
    //give some pixel less to let the iframe fit the screen
    var something = 5;
    //if h is less then 450, resize the iframe 
    if (h < 450 ){
        $('#frame').height(h- something);
        console.log($('#frame').css('height'));
    }else{
        //else, if the iframe height is less then 450, make it bigger
        if(f<450){
            $('#frame').height('450');
        }   
    }
});

anyway, as shown by @timo, it's better to avoid document.write

Upvotes: 3

Related Questions