Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change selected text via javascript

Tags:

window.addEventListener("keydown", function(e){
/*
keyCode: 8
keyIdentifier: "U+0008"
*/
if(e.keyCode === 16 && getSelectionText() != "") {
    e.preventDefault();
      replaceSelectedText(strcon(getSelectionText()));
    }
});

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

function strcon(givenString) {
    var b = '';
    var a = givenString;
    for (i = 0; i < a.length; i++) {
        if (a.charCodeAt(i) >= 65 && a.charCodeAt(i) <= 90) {
            b = b + a.charAt(i).toLowerCase();
        }
        else
            b = b + a.charAt(i).toUpperCase();
    }
    return b;
}

function replaceSelectedText(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = replacementText;
    }
}

The code I have right now seems to change the appearance of the actual text instead of actually changing it. For example, when I'm on Facebook and I press the certain key, the text seems to have changed but then when I press enter, the text goes back to what it was before.

I believe the issue is with the function replaceSelectedText but I'm not sure how to fix it.

Any ideas?

No JQuery please.

https://jsfiddle.net/1rvz3696/

like image 711
Dgameman1 Avatar asked Apr 28 '16 03:04

Dgameman1


1 Answers

You have to get your textarea element to replace the value in it. This is how your replaceSelectedText function should look like,

function replaceSelectedText(text) {
  var txtArea = document.getElementById('myTextArea');
  if (txtArea.selectionStart != undefined) {
    var startPos = txtArea.selectionStart;
    var endPos = txtArea.selectionEnd;
    selectedText = txtArea.value.substring(startPos, endPos);
    txtArea.value = txtArea.value.slice(0, startPos) + text + txtArea.value.slice(endPos);
  }
}

And here's the Fiddle.

Without specific id, you can replace txtArea to this.

var txtArea = document.activeElement;

And another Fiddle

like image 148
choz Avatar answered Sep 28 '22 04:09

choz