Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal at top of iframe regardless of scroll position. How do I position it on screen?

When embedding a Bootstrap app in an iframe, modal dialogs always open at the top of the iframe, not the top of the screen. As an example, go to http://getbootstrap.com/javascript/ and open an example modal on the page. Then using the sample code below which places the same bootstrap page in an iframe, find a modal and open it:

<html>
    <head>
    </head>
    <body>
        <table width="100%">
            <tr><td colspan="2" style="height:80px;background-color:red;vertical-align:top">Here's some header content I don't control</td></tr>
            <tr><td style="width:230px;height:10080px;background-color:red;vertical-align:top">Here's some sidebar content I don't control either</td>
                <td valign="top">
                    <iframe width="100%" height="10000px" 
                        scrolling="no" src="http://getbootstrap.com/javascript/">
                    </iframe>
                </td>
            </tr>
        </table>
    </body>
</html>

Demo in fiddle

How do I go about positioning the modal on the screen in this scenario?

UPDATE: Unfortunately, my iFrame cannot fill the screen, nor can I make it fixed since it needs to blend into the rest of the page and the page itself has enough content to scroll. This is not my design and I ultimately intend to rework the whole thing, but this is what I have to work around for now. As a temporary option, I'm using javascript to tell the iframe parent to scroll to the top where the modal dialog pops up. While this is acceptable, this isn't the desired behavior.

I'm using angularjs and the ui-bootstrap library in my code but as you can see above, it's a bootstrap issue.

like image 829
Charles Josephs Avatar asked Jul 17 '14 13:07

Charles Josephs


1 Answers

If your iframe has the same document.domain as the parent window or it is a sub domain, you can use the code below inside the iframe:

    $('#myModal').on('show.bs.modal', function (e) {
        if (window.top.document.querySelector('iframe')) {
            $('#myModal').css('top', window.top.scrollY); //set modal position
        }
    });

show.bs.modal will fire after you call $('#myModal').show() window.top.scrollY will get the scrollY position from the parent window

In case your document.domain differs from the parent, you can hack it getting the onmousedown position inside the iframe. For example:

$('#htmlElement').on('mousedown', function (event) {
    event.preventDefault();
    $('#myModal').data('y', event.pageY); // store the mouseY position
    $('#myModal').modal('show');
});
$('#myModal').on('show.bs.modal', function (e) {
    var y = $('#myModal').data('y'); // gets the mouseY position
    $('#myModal').css('top', y);
});
like image 194
Rogério Jun Nakatani Avatar answered Sep 18 '22 00:09

Rogério Jun Nakatani