How to detect that a space was backspaced or deleted
Asked Answered
M

4

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.

Mose answered 5/12, 2012 at 17:3 Comment(8)
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?Undulation
do you need detect only space or it might be mixed with text?Predestination
@Predestination I only need to detect a space being removed. I have something else that handles multiple character deletion.Mose
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?Allegorical
What exactly is this for? can you add some context?Allegorical
@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: pastebin.com/QEbpwkn1Mose
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.Mose
@Mose 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.Allegorical
B
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).

Baugher answered 5/12, 2012 at 17:24 Comment(0)
A
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/

Allegorical answered 5/12, 2012 at 17:9 Comment(8)
This doesn't answer the OP's question.Baugher
@Shmiddty: Yes it does, as any removal of a space via any method will show up here.Bronwynbronx
There is nothing here to determine whether or not a space has been removed. This lets you know when ANY character has been removed.Baugher
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.Allegorical
@Baugher 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.Allegorical
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?Mose
@Mose 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?Allegorical
The latest udpate detects if a single space was removed by any means.Allegorical
B
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.

Bronwynbronx answered 5/12, 2012 at 17:11 Comment(3)
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.Mose
Can you provide an example of how I could cache the value beforehand and compare with the value after the keypress?Mose
@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.Bronwynbronx
B
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).

Baugher answered 5/12, 2012 at 17:24 Comment(0)
P
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);
    }
  }

});
Predestination answered 5/12, 2012 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.