0

I implemented a previous answer given here, and now I need to automatically wrap the word around the line instead of always having to manually press the enter key. Any ideas? I'm having quite a bit of trouble with this.

Code:

jQuery('#gift-message-whole-message').on('keypress', function (event) {
                        var text = jQuery('#gift-message-whole-message').val();
                        var lines = text.split('\n');
                        var currentLine = this.value.substr(0, this.selectionStart).split('\n').length;
                        if (event.keyCode == 13) {
                            if (lines.length >= jQuery(this).attr('rows')) return false;
                        } else {
                            if (lines[currentLine - 1].length >= jQuery(this).attr('cols')) {
                                return false;
                            }
                        }
                    });
Community
  • 1
  • 1
  • when typed text goes beyond the col, how are you going to let this piece of code to start a new line as you are consuming/hiding chars beyond that point. I am not clear what you are trying to do. – Alp Jul 29 '15 at 14:20
  • @Alp this makes the text stop appearing on that line when the amount of characters reaches the col value (which is 35 in this case). I'd like to back up one character, insert a hyphen if it's in the middle of a word, and then break the line. All of this happening as the user is typing. Is there a better way of going about this than the answer I came across? – I_Motivate_People Jul 29 '15 at 14:27

1 Answers1

1

Here is the working fiddle for your case.

I slightly changed the else branch as follows:

        if (lines[currentLine - 1].length >= ($(this).attr('cols') - 1)) {
             $('textarea').val($('textarea').val() + "-\n");
//                return false; // prevent characters from appearing
        }

As you can see in the fiddle, code adds a - and a new line, when typed text reaches to col limit. Then it goes on on the next line as user types.

Alp
  • 3,027
  • 1
  • 13
  • 28
  • @I_Motivate_People if this works for you, please accept my answer so that it would be easy for other people to spot it. Thanks. – Alp Jul 29 '15 at 14:43
  • That looks wonderful. Follow up question: if the user decides they don't want the hyphen in the middle of the word and they return the word from the previous line, what would be a good way to remove the hyphen from the word if the word is moved to the next line? – I_Motivate_People Jul 29 '15 at 14:48
  • it is not a technical question but rather a business decision. – Alp Jul 29 '15 at 14:48