Amran Amran - 4 months ago 7
jQuery Question

jQuery - Display Loading Image

I have a

keyup
function to search for a data on a table. I want to make the loading image appear only once. For example, if user type
"one"
, the image will appear only one time until the result appear.

I'am able to show the image upon
keyup
function but it will appear base on what user type. For example, if user type
"one"
, the image will appear 3 times. Below are the example of my codes,

$("#search").keyup(function(){
var search = $("#search").val();
$("#loading").fadeIn(500);
$.post('search_pr.php',
{
search : search
})
.done(function(data){
$("#loading").fadeOut(500);
$("#body").html(data);
});
});

Answer

You can use a flag for this,

var load_img = false;
$("#search").keyup(function(){
   var search = $("#search").val();

   load_img = search.length === 0 ? false : true; // will execute only once
   if(!load_img) {  $("#loading").fadeIn(500); }

   $.post('search_pr.php',
   {
    search : search
   })
   .done(function(data){
    $("#loading").fadeOut(500);
    $("#body").html(data);
  });  
});

However, You should reset that flag load_img to false on focusout or change or blue of the input and when length = 0 as well, so that flag can't bound to only true when it become true when the user type a keyword.

RESET FLAG

$("#search").on("change",function(){
    load_img = false;
});

Hope this helps.

Comments