Search code examples
javascriptjquerycallbackjquery-callback

Call iFrame button and then parent button


I am having a button inside iFrame and a button in a parent window. Button inside iFrame is triggered from parent window. I have certain set of code that is to be executed from both buttons. A part of code is specific to iFrame and a part of code is specific to Parent window. I am able to trigger the iFrame button but the problem is parent window code runs before iFrame button has completed it's operation.

Please help me to achieve this.

Please suggest and thanks in advance.


Solution

  • In the outer document, set up button2 to create a new event containing the chain of actions you want to execute after button1 completes, and dispatch it to the inner button.

    Depending on what actions you want performed, you may have to declare any variables within this click handler that the deferred actions will need so that they are part of the closure.

    $(function(){
        $("#button2").click(function(e){
            var action = function() {
                setTimeout(function(){alert("button2 action")},6000);
            }
            var innerButton = $("iframe#frame").contents()
                .find("#button1");
            e.detail = action;
            var evt = new CustomEvent('click',e);
            innerButton[0].dispatchEvent(evt);
        });
    });
    

    In the inner document, after performing the normal action for the button click, check to see if additional actions were passed with the event, and execute them.

    $(function () {
        $("#button1").click(function (evt) {
            setTimeout(function () {
                alert("button1 click");
                if (typeof evt.originalEvent.detail == 'function') evt.originalEvent.detail(evt);
            }, 3000);
        });
    });
    

    Here are a pair of jsFiddles, one for the inner, and another one for the outer that includes the inner in a (not very legibile) iframe.