[thelist] Javascript: Preview a textarea in another window

Bill Moseley moseley at hank.org
Sat Jan 28 12:09:20 CST 2006


In a CMS-like application, I have a textarea for entering a bit of
html.  I want to have an onclick handler to preview that bit of html
in another window.

What I'd really like to do is have an onclick handler that POSTs just
that textarea and have the response display in another window.  That
way I could filter/validate the content before displaying.



But, first I tried just opening another window and copying the text
from the textarea to a <div> on the opened window:

    function ipreview_page(textarea_id, link) {
        var w = window.open(link,'page_preview', 'width=800,height=600,scrollbars=yes');
        alert('hello');
        w.content.document.getElementById('preview').innerHTML = $(textarea_id).value;
        w.focus();
        return false;
    }

Two problems there.  First, it seems like I need a delay (the alert)
so that the window has time to open.  And second, the focus() doesn't
seem to, well, focus.

Of course, that non-working code doesn't even really address my
initial requirements of passing the text through the server.



After a slow morning on IRC #javascript it was suggested I use onload
instead:

    function preview_page(textarea_id, link) {
        var w = window.open(link,'page_preview', 'width=800,height=600,scrollbars=yes');

        var my_text = $(textarea_id).value;
        var w_onload = w.onload;
        var my_onload = function() {
            w.content.document.getElementById('preview').innerHTML = my_text;
            if ( typeof p_onload == 'function' ) {
                w_onload();
            }
            w.focus();
        };
        w.onload = my_onload;

        return false;  /* And this doesn't focus the window */
    }

But, that only works when the window is first opened.





-- 
Bill Moseley
moseley at hank.org




More information about the thelist mailing list