Stop page refresh on field focus

I am using the following function (With help from Paul Wilkins) to refresh dynamic loaded content every 10 seconds:


$(function () {
    var timer,
        updateContent;

    function resetTimer() {
        if (timer) {
            window.clearTimeout(timer);
        }
        timer = window.setTimeout(updateContent, 10000);
    }

    updateContent = function () {
        resetTimer();
        $.get('modules/berichten.php', function (data) {
            $('#main').html(data);
        });
    };
    updateContent();
    $(document.body).on('mousemove keydown', resetTimer);
});

The timer will be reset when there is mouse movement or when there are key strokes. I was wondering if it is possible to reset the timer when a certain textfield or text area is in focus?

Thank you very much

I tried to add the following to the above function:

	$('#bericht_form').focus(function () {
		window.clearTimeout(timer);		
	});

It doesn’t give me an error, but it isn’t working either. What is the right syntax for this or should I change the entire function

You can’t listen to focus on a form element. Instead you should listen to focus events on the children within that form. So $(‘#bericht_form :input’) instead of $(‘#bericht_form’) in your code should work.

In case you’re wondering, :input selects all input, textarea, select and button elements.
(copied verbatim from the manual)

Hi ScallioXTX. Thanks for the reply and tip :tup:. I tried two different methods at the end of the function:


	$('#bericht_form :input').focus(function () {
		window.clearTimeout(timer);		
	});

and


	$('#bericht_form :input').focus.window.clearTimeout(timer);

but none is giving me the desired result

The first one should work.

If you do it like this


$('#bericht_form :input').focus(function () {
    console.log("Input focussed!");
    window.clearTimeout(timer);
});

Do you see anything in your console when you focus an element?

It states Input focussed! So it should be working one would think, but I see on certain other elements that the page is refreshing

Hi donboe,

Can you post a link or enough code to recreate your problem?