Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to turn off spell check in a textarea? [duplicate]

I run into this problem. I have a textarea which I only want to use spell check when it's in focus.

<textarea id="editor"></textarea>

$('#editor').focusin(function(){
    $(this).attr('spellcheck', true);
});

$('#editor').focusout(function(){
    $(this).attr('spellcheck', false);
});

In chrome, if a word is misspelled there is a red line under the word. Even if I turn off the spell checker, the red line still exists. How do I remove this marker?

like image 908
Charlie Wu Avatar asked Jun 18 '12 05:06

Charlie Wu


2 Answers

I used this question to get an answer to your question: Force spell check on a textarea in WebKit

HTML:

<textarea id="editor" spellcheck="true"></textarea>

Javascript:

$('#editor').focusin(function(){
    $(this).attr('spellcheck', true);
});

$('#editor').focusout(function() {
    $(this).attr('spellcheck', false);
    forceSpellcheck($(this));
});

    var canCheck = true;
    function forceSpellcheck($textarea) {
  if (canCheck) {
    canCheck = false;

    $textarea.focus();
    $textarea.attr('spellcheck', false);
    var characterCount = $textarea.val().length;

    var selection = window.getSelection();
    for (var i = 0; i < characterCount; i++ ) {
      selection.modify("move", "backward", "character");
    }

    // Remove focus from the element, since the word under
    // the cursor won't have a misspelling marker.
    $textarea.blur();
  } else {
    canCheck = true;
  }
}​

Demo: http://jsfiddle.net/QgsRU/13/

like image 123
Chango Avatar answered Nov 13 '22 05:11

Chango


got it figured out

function bindEditorFocus() {
    var $editor = $('#editor');
    $editor.focusin(function(){
        $(this).attr('spellcheck', true);
        toggleSpellingcheck(); // loop through all words to add marker
    }); 
    
    $editorblur(function(){
        $editor.attr('spellcheck', false);
        $editor.unbind();    // I need to unbind all function to avoid a loop 
        toogleSpellingcheck(); // loop through all words to remove marker
        $editor.blur();     //get out of text area
        bindEditorFocus();  // rebind all functions 
    });
}


function toogleSpellingcheck(){ 
    //this will loop through all words
    var $editor = $('#editor'); 
    var text = $editor.val();       
    for (var i = 0; i < text.length; i++) {
        $editor.caret({start:i,end:i});
    }
}

the toogleSpellingcheck method loop through all words, it can be optimized to loop through words instead of characters, but this would need the jquery caret plugin

it's a bit messy, but works, anyone got suggestions on improvements please let me know

like image 45
Charlie Wu Avatar answered Nov 13 '22 04:11

Charlie Wu