简体   繁体   中英

Call user defined jQuery function with JS

I use a jQuery window libray https://github.com/humaan/Modaal

which triggers events this way $("class of element").modaal({arg1, arg2,...});

--- I updated my question here to make it more general and used an iframe / Html instead of an external svg ---

To trigger an element eg in an external Html which is loaded within an iframe, I applied the following code to the iframe:

<iframe src="External.html" id="mainContent" onload="access()"></iframe>

which calls this function:

function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}

Actually it will only work on every second click. Any idea what I did not consider properly?

Best

You do not need to wait windows loading but iframe only:

$(function() {
    $("#mainContent").bind("load",function(){
        var myIframeElement = $(this).contents().find(".modaal");

        myIframeElement.modaal({
            content_source: '#iframe-content',
            type: 'inline',
        });
    });
});

The reason why it did not work was that the iframe was not completely loaded, while jQuery tried to attach the function. As $(document).ready(function(){} did not work, the workaround was to initialize it with

$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});

This worked properly to attach the functionallity to an element within the iframe.

Actually modaal will vanish the envent handler after the overlay was opened and closed again. So maybe someone wants to trigger an iframe element for modaal, too, here is a setup which would solve this issue. (It can be optimised by @SvenLiivaks answer):

 $(window).on("load", function() {
     reload();
    });

function reload() {
    var length = $("#iframeID").contents().find("#IDofDIVelement").length;
    // The following check will return 1, as the iframe exists.
    if (length == 0) {
        setTimeout(function() { reload() }, 500);
    } else {
        $("#iframeID").contents().find("#IDofDIVelement").modaal({
            content_source: '#modalwrapper',
            overlay_close: true,
            after_close: function reattach() {
                reload();
            }
        });
    }
}

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