Homer
Homer

Reputation: 355

rewrite an Immediately-Invoked Function

I've got a script from AWeber, for a popup form, and I want to customize it a little bit..

It currently opens the popup when the page loads. I want it to run as a click event for a button.

The problem is: it uses an immediately-invoked function. And since I'm a newbie and not familiar with this kind of pattern yet, I can't figure it out. I've read about it, but I'm still not completely understanding it.

So, I've tried to rewrite the script to a simple pattern, but it doesn't work!

So, would you please help figuring out what the problem is with my new function?

And/or simplify/explain the other function for me?

The first Function:

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//forms.aweber.com/form/id.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, "script", "aweber-wjs-formid")

My attempt (jQuery) :

function createAweberScript() {
    var script=document.createElement('script');
    script.type='text/javascript';
    script.id='aweber-wjs-formid';
    script.src='//forms.aweber.com/form/id.js';
    jQuery('body').append(script);
}

jQuery(document).ready(function () {
    jQuery( 'a.button' ).click(createAweberScript);
});

Upvotes: 1

Views: 59

Answers (1)

elixenide
elixenide

Reputation: 44833

Just wrap the immediately-invoked function in a regular function, and call that function in the click handler:

function createAweberScript() {
    // start Aweber script
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//forms.aweber.com/form/id.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, "script", "aweber-wjs-formid"));
    // end Aweber script
}

jQuery(document).ready(function () {
    jQuery('a.button').click(createAweberScript);
});

You could pick this apart and write your own function, yes, but this is easier to understand and maintain: if the Aweber function ever changes, you just have to replace everything inside your createAweberScript() function to update it.

Note: I got a 404 for http://forms.aweber.com/form/id.js; I'm assuming that's not really the URL you are trying to use. If so, you might want to check it.

Upvotes: 5

Related Questions