Alist3r
Alist3r

Reputation: 556

Jquery/Javascript: do something based on user typing time?

Assuming i've this simple html:

<input type="text" id="inputId" /><img id="imgId" src="images/myImage.gif" style="display:none" />

now i want to do this:

1) When someone write in the input i want to show the image 1) When the user stop to write in the input or the input is empty for 1-2 seconds i want to hide the image

i Know how to show or hide the image:

$('#imgId').css('display', '')

or

$('#imgId').css('display', 'none')

but i don't know how to add the timing.

Thanks

Upvotes: 0

Views: 68

Answers (3)

Pratik Joshi
Pratik Joshi

Reputation: 11693

Use keydown(),keyup() events

$( "#inputAreaID" ).keydown(function(){
    $('#imgId').css('display', 'block')
});

$( "#inputAreaID" ).keyup(function(){
    $('#imgId').css('display', 'none')
});

Upvotes: 0

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

Somethingk like that

var initial;

function invocation() {
    initial = window.setTimeout( 
    function() {
        $("#imgId").hide();
    }, 2000);
}



$('#inputId').keypress(function() {

    $("#imgId").hide();
    clearTimeout( initial );
    invocation();
});

see jsFiddle

Upvotes: 1

Joseph Dailey
Joseph Dailey

Reputation: 4925

you can use window.setTimeout(myfunction, delay) and restart the timeout every change of the input. So after 2 seconds of no input myfunction will execute. Comment if you would like help writing it.

Also jquery has hide() and show() functions instead of manually changing the css.

Upvotes: 0

Related Questions