Ronald
Ronald

Reputation: 16383

Attaching a function to the parent window from an iframe and getting proper scope

I working on adding file uploading to my web application. I'm using an iframe to post my upload. When my php script processes the upload it writes some JavaScript to the iframe. This JavaScript is attempting to attach a function to the parent, this works, but when this function actually gets called it doesn't have the correct scope. Here is the code I'm attaching to the parent window:

parent.window.showPreview = function(coords)
{
    if (parseInt(coords.w) > 0)
    {
        var rx = 200 / coords.w;
        var ry = 250 / coords.h;

        $('#preview').css({
            width: Math.round(rx * 400) + 'px',
            height: Math.round(ry * 533) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    }
}

When this function gets executed I get an error that says $ is not defined. I've tried adding changing the JQuery call to parent.$('#preview').css..., but then it says that parent is undefined. Any ideas?

Upvotes: 1

Views: 822

Answers (1)

Pointy
Pointy

Reputation: 413737

Try this:

var p$ = parent.window.$;
parent.window.showPreview = function(coords) {
    if (parseInt(coords.w) > 0)
    {
        var rx = 200 / coords.w;
        var ry = 250 / coords.h;

        p$('#preview').css({
            width: Math.round(rx * 400) + 'px',
            height: Math.round(ry * 533) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    }
}

If you're making a function for the parent window, you probably want it to use the parent window's jQuery instead of the child window's. You'll also need to make sure the parent page has its own copy of jQuery. (If it doesn't, and you're brave, you could try dynamically giving it one!)

edit

Here's how you could do it with a closure instead of the global p$:

parent.window.showPreview = (function(p$) {
  return function(coords) {
    // ... same as above
  };
})(parent.window.$);

Upvotes: 1

Related Questions