简体   繁体   中英

Access parent window scroll event from child inside iframe with Jquery

I have a small javascript/jquery script on page1 (an aspx page) that scrolls an iframe loaded with page2 so that it stays with you on the page as you scroll up and down page1. However, when I load page1 inside an iframe for another parent page the scroll affect doesn't work.

I've tried using window.parent in the calls, but the script still doesn't activate and scroll the page2 iframe as you scroll page1 within the iframe of the parent page (another aspx page). I hope that makes sense.

Here is the script I've tried:

<script type="text/javascript">
        $(window.parent.document).ready(function () {
            var $scrollingDiv = $("#IframeDir");

            $(window.parent).scroll(function () {
                $scrollingDiv
                .stop()
                .animate({ "marginTop": ($(window.parent).scrollTop() + -10) + "px" }, "slow");

            });
        });


    </script>

It works if I just load page1 in it's own tab or window, but if I load page1 within an iframe into the parent page, it doesn't seem to see the scroll event of the parent page.

Thanks in advance for any suggestions! Erin

See this answer Run JQuery in the context of another frame

You have to pass in the context to search in (the parent document)

// Untested
$(window.parent.document, window.parent.document).ready(function () {
    var $scrollingDiv = $("#IframeDir");

    $(window.parent, window.parent.document).scroll(function () {
        $scrollingDiv
        .stop()
        .animate({ "marginTop": ($(window.parent, window.parent.document).scrollTop() + -10) + "px" }, "slow");

    });
});

I also wanted the floating div within iframe and Rantul this code worked for me!

$(parent.window).scroll(function() {
   //parent document scroll functions go here
});

I don't think you can call $(window.parent).scroll() from within $(document).ready() or in this case $(window.parent.document).ready() . For that matter I don't think $(window.parent).scroll() will work at all I think it needs to be $(parent.window).scroll()

This is how I've done it before:

$(document).ready(function() {
//document ready functions go here
});

$(parent.window).scroll(function() {
//parent document scroll functions go here
});

And to answer your other question, I do believe you need jQuery on the parent page as well for this to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM