6

I need to find a way to detect if a space was deleted or backspaced, and run a function if that is the case. I am working on this in JavaScript / jQuery.

I know I can get the delete or backspace key press by using:

$(this).keyup(function(event) {
        event.keyCode

However, I do not know how to tell if the delete or backspace command removed a space?

Very appreciative for any suggestions.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Baxter
  • 5,633
  • 24
  • 69
  • 105
  • When you detect a backspace or a delete key pressed you check the current position of the caret in your input element and check if before/after it is a space that will be deleted? – koopajah Dec 05 '12 at 17:07
  • do you need detect only space or it might be mixed with text? – dmi3y Dec 05 '12 at 17:08
  • @dmi3y I only need to detect a space being removed. I have something else that handles multiple character deletion. – Baxter Dec 05 '12 at 17:11
  • what if a space AND a character was removed? why would you need to detect these two things separately? wouldn't it make more sense to detect both at once? – Kevin B Dec 05 '12 at 17:13
  • What exactly is this for? can you add some context? – Kevin B Dec 05 '12 at 17:14
  • @KevinB I am working on a jQuery plugin to count / limit the number words in a textarea. Here is the plugin code as it stands now: http://pastebin.com/QEbpwkn1 – Baxter Dec 05 '12 at 17:26
  • To limit the user from entering anymore characters the value of the textarea is reset to obj.val(limited); if the user is >= the limit. This works great except for when I have reached the word limit and move my cursor to a word in the middle of the word string and try and backspace/delete a word. Since the word limit is met it keeps firing the wordCount() function and moving my cursor to the end of the last word. So my thought was to ignore backspace / delete unless they remove a space which is the division between all words, at that point I would want to re-count the number of words. – Baxter Dec 05 '12 at 17:34
  • @Baxter With that in mind, my keydown with setTimeout won't work because by the time you detect that it is the space that was removed, the event has already occurred meaning you can't prevent the event, you can only undo it resulting in the insertion point going to the end. – Kevin B Dec 05 '12 at 19:14

4 Answers4

2

Bind to the keydown and compare the value from before and after to see if it reduced in size.

$(input).keydown(function(){
    var currVal = this.value, self = this;
    setTimeout(function(){
        if ( currVal.length > self.value.length ) {
            console.log(currVal.length - self.value.length + " characters have been removed.");
        }
    },0);
});

http://jsfiddle.net/ymhjA/1/

Updated sample:

$("input").keydown(function() {
    var currVal = this.value,
        self = this;
    setTimeout(function() {
        if (currVal.length - self.value.length === 1) {
            var origVal = $.grep(currVal.split(""),function(val){
                return val === " ";
            });
            var newVal = $.grep(self.value.split(""),function(val){
                return val === " ";
            });
            if ( origVal.length != newVal.length ) {
                console.log("a space was removed");
            }
        }
    }, 0);
});​

http://jsfiddle.net/ymhjA/4/

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • This doesn't answer the OP's question. – Shmiddty Dec 05 '12 at 17:12
  • @Shmiddty: Yes it does, as any removal of a space via any method will show up here. – Phil H Dec 05 '12 at 17:13
  • There is nothing here to determine whether or not a space has been removed. This lets you know when ANY character has been removed. – Shmiddty Dec 05 '12 at 17:15
  • If he wanted to reduce it down to only the delete key and backspace, he would just have to look at the `event.which` property. – Kevin B Dec 05 '12 at 17:15
  • @Shmiddty The only way to do that would be to add a for loop going through each character to see if the character that was removed was a space. before i write something like that i'd rather have some clarification from the OP. – Kevin B Dec 05 '12 at 17:17
  • Won't that just tell me if the string as a whole has been reduced in size? How will this tell me if a space was just deleted or backspaced so I can run a function in that case? – Baxter Dec 05 '12 at 17:18
  • @Baxter You would have to loop through every character in the string until you find the one (or many) that was removed. Does this need to handle the case where more than 1 character is removed with one of them being a space? – Kevin B Dec 05 '12 at 17:19
  • The latest udpate detects if a single space was removed by any means. – Kevin B Dec 05 '12 at 17:28
2

Cache the value beforehand (set a value on keypress) and compare with the value after keypress. That is the only way to know with certainty that one or more spaces has been removed. Any checking of keys relies on you being able to work out what possible keys could achieve the removal of a space, and will likely leave holes.

As an example, selecting the final letter of a word and the space following it, if we press the last letter it will remove the space. But the key pressed is not backspace or delete.

Phil H
  • 19,928
  • 7
  • 68
  • 105
  • That is fine, every other character calls the function on keyup(). I want to treat backspace and delete differently and only call the function if delete or backspace removed a space otherwise I want to ignore those commands. – Baxter Dec 05 '12 at 17:16
  • Can you provide an example of how I could cache the value beforehand and compare with the value after the keypress? – Baxter Dec 05 '12 at 17:17
  • @KevinB: indeed. I saw your answer appear as I was posting mine, and it does exactly that. Could perhaps make it synchronous by messing about with the event.prototype and catching it a second time in the event bubble, but that would be a lot more effort and questionable. – Phil H Dec 05 '12 at 17:21
2

See here: http://jsfiddle.net/Txseh/

(function(){
    var currentWhitespaceCount;

    $("input").keyup(function(e){
        var newCount = ($(this).val().match(/\s/g) || []).length;

        if (newCount < currentWhitespaceCount)
            alert("You removed one or more spaces, fool.");

        currentWhitespaceCount = newCount;
    });
})();​

It tracks the current number of whitespace characters in the input, and if ever the number goes down, it alerts(or does whatever you want).

Shmiddty
  • 13,847
  • 1
  • 35
  • 52
1

actually here is my code http://jsbin.com/atuwez/3/edit

 var input = $('#input'),
     afterLength,
     beforeLength;

input.on({
  'keydown': function () {
    beforeLength = input.val().split(/\s/).length;
  },
  'keyup': function(event) {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 ) {
          afterLength = input.val().split(/\s/).length;
          console.log(beforeLength == afterLength);
    }
  }

});
dmi3y
  • 3,482
  • 2
  • 21
  • 32