Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing textarea wrapping using javascript

Tags:

javascript

dom

For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:

  <form name="wikiedit" action="[[script_name]]" method="post">
    <textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
    <input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp;
    <input type="submit" value="Save">
  </form>

It works with IE, but not with Firefox or Opera. How should I do this?


1 Answers

See bug 41464: https://bugzilla.mozilla.org/show_bug.cgi?id=41464

Nasty workaround for now is to replace the textarea with a clone of itself:

function setWrap(area, wrap) {
    if (area.wrap) {
        area.wrap= wrap;
    } else { // wrap attribute not supported - try Mozilla workaround
        area.setAttribute('wrap', wrap);
        var newarea= area.cloneNode(true);
        newarea.value= area.value;
        area.parentNode.replaceChild(newarea, area);
    }
}

Unrelated: try to avoid accessing elements straight out of the document object, it is unreliable on some browsers and causes name clash problems. ‘document.forms.wikiedit’ is better, and moving to ‘id’ on the form instead of ‘name’ and then using ‘document.getElementById('wikiedit')’ better still.

form.elements.content is also more reliable than form.content for similar reasons... or, indeed, you could give the textarea an ID and go straight to the textarea with getElementById without having to bother look at the form.

like image 156
bobince Avatar answered Jul 14 '26 04:07

bobince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!