Cannot figure out when to hide and show loading animation with JQuery

↘锁芯ラ 提交于 2019-12-20 04:38:45

问题


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>


来源:https://stackoverflow.com/questions/6158072/cannot-figure-out-when-to-hide-and-show-loading-animation-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!