Philll_t
Philll_t

Reputation: 4437

How to add script to an iframe and then adding an element to trigger it

(using jquery or just js) Is it possible to add script to an iframe and then add an element to trigger it? This adds the script but it gives me an error in Chrome saying that the function is undefined.

        //create element
        var cloned = $("<input type='button'/>")

        cloned.attr('onclick', "alertUser()");
        var parent = $("#parent");
        var iframe = $('<iframe />').attr("id", "rbm_pu");
        parent.append(iframe);
        var frame = $("#rbm_pu").contents();
        frame.find("body").append(cloned);
        frame.find('body').append("<script type='text/JavaScript'>function alertUser(){alert('hello');}</script>");

It appears in there but says that alertUser() is undefined. Any ideas? Thanks

Upvotes: 0

Views: 238

Answers (1)

Pavel S.
Pavel S.

Reputation: 12322

This fiddle should lead you to the correct way: http://jsfiddle.net/vsXYA/2/

<div id='parent'></div>

// first, create button and assign the callback
var button = $("<input type='button' value='click me' />");
button.click(function() {
    alert("hello");
});

// then, append the button to the freshly created iframe
$('<iframe id="someId"/>')
    .appendTo('#parent')
    .contents().find('body')
    .append(button);

If you insist on defining the function as a string (and I strongly discourage you from doing that), this works: http://jsfiddle.net/vsXYA/5/

(Took some info from https://stackoverflow.com/a/4120007/729403 and https://stackoverflow.com/a/3603496/729403)

Upvotes: 1

Related Questions