Cannot figure out when to hide and show loading an

2019-03-01 00:57发布

问题:

I have a loading animation which I initially hide in my application.js file:

$('#loading_field').hide();

I have an autocomplete field, and I want the animation to appear when the user starts typing, and for it to disappear when the autocomplete suggestion results appear. Below is my jquery code for the jquery ui autocomplete plugin:

$(".showable_field").autocomplete({
    minLength: 1,
    source: '/followers.json',
    focus: function(event, ui) {
       $('.showable_field').val(ui.item.user.name);
       return false;
    },
    select: function(event, ui) {
        var video_id = $('#video_id_field').val();
        var user_id = ui.item.user.id;
        $.post("/showable_videos.js", {video: video_id, user: user_id});
        $(':input','#new_showable_video').not(':button, :submit, :reset, :hidden').val('');
        return false;
    }
});
var obj = $(".showable_field").data('autocomplete');
obj && (obj._renderItem = function( ul, item ) {
    return $( "<li></li>" )
       .data( "item.autocomplete", item )
       .append( "<a>" + item.user.name + "</a>" )
       .appendTo( ul );
});

Where should I show and hide the animation?

回答1:

Because you're using AJAX to load the suggestions I think this should work for you:

$('#loading_field').ajaxStart(function () {
  $(this).show();
}).ajaxStop(function () {
  $(this).hide();
});


回答2:

Well, jQuery UI automatically adds the class 'ui-autocomplete-loading' to your input when it is loading remote data, so the absolute easiest way to do this is to simply put an animated GIF in as the background image on your input when that class is present.

That's what they do in the remote-loaded example on jQueryUI.com (note that you have to type two more more characters to kick off the ajax call in this example).

<style>
  .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>