views:

193

answers:

1

Background story: when a user selects a portion of text in a text field with her mouse (mark it up manually), and subsequently hits "alt" key, a certain function would trigger.

My questions are:

  • How can I trigger a function when a user hits a key (in her keyboard)?
  • How can I preserve a portion of text selected, and use it as a parameter for that function?

I've tried looking up online but haven't found any good answers, but i'd greatly appreciate links as well.

+3  A: 
$(document).keydown(function(event){
    if (event.altKey) {
        var text = $.trim(getSelectedText());
        if (text.length) {
            console.log(text);
        }
    }
});

function getSelectedText() { 
    if (window.getSelection) { 
        return window.getSelection().toString(); 
    } else if (document.getSelection) { 
        return document.getSelection(); 
    } else if (document.selection) { 
        return document.selection.createRange().text; 
    } 
} 

If you want to get the selected text in a text input or textarea you can do this:

$(':text, textarea').keydown(function(event){
    if (event.altKey) {
        var text = '';
        if ('selectionStart' in this){
            var length = this.selectionEnd - this.selectionStart;
            text = $.trim($(this).val().substr(this.selectionStart, length));
        } else if (document.selection) {
            text = $.trim(document.selection.createRange().text);
        }
        if (text.length) {
            console.log(text);
        }
    }
});
PetersenDidIt
Thanks a lot for the answer. I tried to do this with alert(text) but it alerted nothing. Why do you think this happens?
sombe
Is something selected when you hit the alt key?
PetersenDidIt
yes, there was. i wrote down "this is awesome" in an input field, marked it up, hit alt and it alerted nothing (I put the alert right after the nested if inside the .keydown function.(I does alert, but nothing shows up in the alert box).
sombe
and plus, for some reason it alerts it like 4 times, I'm not sure why that is...
sombe
Wait! It does work, but when I markup text that's already written into the document. But written text (as into field) that I markup, it does not alert.
sombe
Ahh it being in a textarea or field is key information
PetersenDidIt
Yeah that's right, I should have emphasized it. Do you think there's a way to accomplish this?
sombe
Btw are you familiar with a way to get the value of content typed in a text field?
sombe
Updated the answer to show a way to get the selected text of a text input and textarea. To get the valu of the text field just do something like: `$('#myField').val();`
PetersenDidIt
Thank you! This works smoothly now. I appreciate all your help.
sombe