Try this, I'm not sure how to get it working on mobile yet, but it should bring you a whole lot closer to functioning code:
$('#input').on('keydown',function(e) {
var pos = this.selectionDirection=='backward' ? this.selectionStart : this.selectionEnd;
if ((e.which==8 && pos!=0) || (e.which==46 && pos!=$(this).val().length)) { //BACKSPACE or DELETE
$('#output img').last().remove();
}
});
$('#input').on('keypress',function(e) {
if (e.which!=13) { //ENTER
$('#output').append('<img src="http://www.w3schools.com/tags/smiley.gif" alt="" width="15" height="15">');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input" type="text" />
<div id="output"></div>
- The
e.which==8
and the other numbers are used to check for a certain keycode, which corresponds to a key on your keyboard (list of keycodes).
- I changed your
keyup
to keypress
, otherwise a smiley would also be inserted on pressing keys like Ctrl, Alt, Shift, etc (more info).
However, Enter does get registered on keypress
, so I placed the .append(
inside the if (e.which!=13) {
, otherwise a smiley would be added every time you press Enter, while nothing happens in the <input/>
since it doesn't support multiple lines.
- I added a
keydown
handler for Backspace and Delete:
- This handler checks if Backspace or Delete are pressed, but also checks that the caret (cursor) isn't respectively at the start or at the end of the
<input/>
text.
- Otherwise a smiley would be removed when you press Backspace when the cursor is at the start, while no actual character would be removed from the
<input/>
, creating inconsistencies. Same goes for Delete at the end of the <input/>
.
- That
var pos =
line handles selection of the <input/>
text. I got it from this comment by @And390. Although I don't think it really does it's work here, but you can build on this, see the last paragraph of my answer.
And if you don't understand the ?
and :
, it's called a ternary operator, read that link if you want to understand it.
It isn't 100% foolproof, for instance if you select multiple characters and delete them, only one smiley is removed. Same goes for pasting multiple characters. And if you select one character and insert the exact same character in it's place (so the text doesn't actually change), there will still be a smiley added.
To fix those kinds of bugs, you could try using this post or others concerning caret position and input selection.
You can also try using .on('input',
instead of 'keypress'
, maybe that gives better results for your needs; 'input'
doesn't look so much at what keys are pressed, but instead at what actually is entered into the input-field.