This is my code:
// Refresh feeds, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
$("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
I'm working on a kind of "wall" like Facebook where you can comment on each other's posts. The wall automatically refreshes with AJAX (every 9 seconds), but when you're typing and the textfield is focused it removes the focus and the content of the textbox after the page refreshed.
How can I make it only refresh when you're NOT typing and make it stop when you're typing. Thanks! I've looked everywhere and tried everything, but no luck.
You should keep a timeout
timer running when they type, and check before you load:
var typing = false,
theTimer,
refreshId = setInterval(function() {
typing || $("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
$('#theInput').keyup(function() {
typing = true;
theTimer && clearTimeout(theTimer);
theTimer = setTimeout(function() {
typing = true;
}, 500);
});
I suppose you have an input box like this:
<input type="text" id="input-box" ... />
All you have to do is mantain a global variable than says if this input has the focus:
var isTyping = false;
$("#input-box").focus(function() {
isTyping = true;
});
$("#input-box").blur(function() {
isTyping = false;
});
then you just have to check this variable before to allow the update:
// Refresh feeds, but ONLY when you are NOT typing
var refreshId = setInterval(function() {
if (!isTyping) {
$("#load-feeds").load('/actions/loadfeed.php?randval='+ Math.random());
}, 9000);
}
$.ajaxSetup({ cache: false });