2014-10-22 22 views
7

Una volta cercavo una soluzione per il mio problema e il mio problema era "Voglio rilevare quando l'utente sta digitando e quando smette di digitare in modo da poter aggiornare lo stato."Rileva quando l'utente inizia/interrompe la digitazione in jquery

Ho creato un campione. Che possa funzionare per te.

var typingTimer; 
var doneTypingInterval = 10; 
var finaldoneTypingInterval = 500; 

var oldData = $("p.content").html(); 
$('#tyingBox').keydown(function() { 
    clearTimeout(typingTimer); 
    if ($('#tyingBox').val) { 
    typingTimer = setTimeout(function() { 
     $("p.content").html('Typing...'); 
    }, doneTypingInterval); 
    } 
}); 

$('#tyingBox').keyup(function() { 
    clearTimeout(typingTimer); 
    typingTimer = setTimeout(function() { 
    $("p.content").html(oldData); 
    }, finaldoneTypingInterval); 
}); 



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 



<textarea id="tyingBox" tabindex="1" placeholder="Enter Message"></textarea> 
<p class="content">Text will be replace here and after Stop typing it will get back</p> 

View on Fiddle : http://jsfiddle.net/utbh575s/

+0

Benvenuti in SO! Qual è la tua domanda? – georg

+0

Il tuo codice funziona ... Qual è lo scopo di questa domanda? – rinuthomaz

+3

Ciao, sì, funziona così perché l'ho condiviso. Possa essere utile anche per gli altri. –

risposta

4

Forse ciò che si vuole è la antirimbalzo funzionalità.

In pratica limita la velocità di attivazione di una funzione. Quindi attende alcuni ms prima di sparare all'evento come se l'utente interrompesse il processo di scrittura.

controllare questo frammento

// Returns a function, that, as long as it continues to be invoked, will not 
 
// be triggered. The function will be called after it stops being called for 
 
// N milliseconds. If `immediate` is passed, trigger the function on the 
 
// leading edge, instead of the trailing. 
 
function debounce(func, wait, immediate) { 
 
\t var timeout; 
 
\t return function() { 
 
\t \t var context = this, args = arguments; 
 
\t \t var later = function() { 
 
\t \t \t timeout = null; 
 
\t \t \t if (!immediate) func.apply(context, args); 
 
\t \t }; 
 
\t \t var callNow = immediate && !timeout; 
 
\t \t clearTimeout(timeout); 
 
\t \t timeout = setTimeout(later, wait); 
 
\t \t if (callNow) func.apply(context, args); 
 
\t }; 
 
}; 
 

 
// This will apply the debounce effect on the keyup event 
 
// And it only fires 500ms or half a second after the user stopped typing 
 
$('#testInput').on('keyup', debounce(function() { 
 
    alert('typing occurred'); 
 
    $('.content').text($(this).val()); 
 
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="testInput" /> 
 

 
<p class="content"></p>

Fondamentalmente ora tocca a voi. Imposta il tuo tempo in ms e sei a posto.

+1

Utile davvero. Grazie – Gateway