user398341
user398341

Reputation: 6577

jQuery delay and keyup

HI guys,

What I'm trying to do is to display the animated gif while someone is typing text into the text field with keyup and once they've finished typing, the gif to disappear and display message 'Saved' for a few seconds, which would then disappear.

What I've done so far is:

if ($('.gallery_items li input').length > 0) {
    $('.gallery_items li input').keyup(function() {         
        var li = $(this).parent();
        li.children('.gallery_saving').removeClass('dn');
        var identity = li.attr('id').split('_');
        var v = $(this).val();
        var url = '/caption/id/' + identity[1];
        $.post(url, { caption : v });   
        $.delay(500).li.children('.gallery_saving').delay(500).html('Saved...').delay(500).addClass('dn');          
        return false;
    });
}

Where class 'gallery_saving' has animated gif assigned as background image and class 'dn' has simply css 'display:none'. Initially 'gallery_saving' has class 'dn' as well - so that it isn't visible, when someone starts typing the class 'dn' is removed - showing the loader.

You obviously see the problem already with:

$.delay(500).li.children('.gallery_saving').delay(500).html('Saved...').delay(500).addClass('dn');

and I know it's wrong, but can't figure out how to do it - can anyone help?

Upvotes: 0

Views: 831

Answers (2)

gabel
gabel

Reputation: 512

You should remove the loader not on delay time, but on succesful safe of the entered data..

Something like

url = "/echo/html";
v = "test";
$.ajax({
  url: url,
  type: 'POST',
  data: ({ caption: v}),
  success: function(){
    $('.gallery_saving').html('Saved...').delay(1000).fadeToggle("slow");
  },
  error:  function() {
    $('.gallery_saving').html('Error...').delay(1000).fadeToggle("slow");
  }
});

Example: http://fiddle.jshell.net/gabel/udvbx/

Read http://api.jquery.com/jQuery.ajax/ for Details...

Upvotes: 1

Calum
Calum

Reputation: 5316

It's not a particularly good idea to try and do this, because you'll end up making a lot of ajax calls if the user hasn't actually finished typing. If the user is a slow at typing, you will be saving the data a lot of times for no reason.

You could also use show() and hide() instead of the dn class. Or use toggleClass()

Upvotes: 1

Related Questions