So i'm working on something where i want to fire off an event (client-side, JavaScript) in two scenarios:
- If the user has finished typing a word, e.g: "stack " (fired, with "stack" as a word)
- If 2 seconds has passed. This will handle the "last word". (e.g no space after)
So, to sum up, here's how it would fire as i'm typin开发者_StackOverflowg:
"Stack " (req #1 fired - "Stack")
"Overflow " (req #1 fired - "Overflow")
" Rocks" (req #3 fired - "Rocks")
Hopefully that makes sense.
So, off the top of my head, i'm thinking i would need to hook into the .keypress()
event (i'm using jQuery BTW), and then do some string magic (e.g look for spaces, etc)
Is it that simple? Or is there something out there (e.g an "extended" .keypress()
handler) that has already done this?
I would :
- Register to the input keyup event
$("input").bind("keyup", function(e){ });
- Check if the pressed key is the space bar
if(e.keyCode == 32)
- If it is, get the last word from the input
$("body").trigger('input_update', { last-word: false, word: $(this).val()).replace(/[\s-]+$/,'').split(/[\s-]/).pop() });
For the 2s timer, just launch a timer when the page is ready, and reset it each time the keyup event on the input is triggered. Reaching, those 2s, the function executed should be like that : function(){ $("body").trigger('input_update', { last-word: true, word: $(this).val()).replace(/[\s-]+$/,'').split(/[\s-]/).pop() }); }
And before all that, register to your custom event : $("body").bind("input_update", function(e, data){ // do your stuff with the last word });
The code may not be 100% correct since i'm tired, but you got the idea.
I don't know if something like that is done already, but there is an easy way to sort it out, check this fiddle.
精彩评论