Limit ajaxStart function to only 1 of 2 ajax functions

I have a loading.gif that launches each time the user makes an AJAX powered search. However, I've got some search fields that automatically show suggestions while the user types, also powered by AJAX.

Now my loading.gif appears on the user search as well as the search suggestions while typing. How do I limit my function that shows the loading.gif to only show when it's a user AJAX search and not a search-suggestion-while-typing AJAX search?

This is my function:

$(document).ajaxStart(function () {
    $(".se-pre-con").fadeIn("fast");
}).ajaxStop(function () {
    $(".se-pre-con").fadeOut("fast");
});

Answers 1

  • how about bind it with condition like if user is still on the search input then dont show the loading.gif else if the user is out of the search input or first contact on the search input then show the loading.gif (refer below)

    first the global variable

    var input_focus = false;
    

    and then when the specified input is on focus

    $("#specified_input").focus(function(){
        //set the variable named 'input_focus' to true to reject the showing of the loader (loading.gif) or hide it.
        input_focus = true;
    }).blur(function(){
        //when the specified input lose it focus then set the variable 'input_focus' to false so that the loader (loading.gif) is allowed to show
        input_focus = false;
    });
    
    $.ajax({
        url : 'my-url',
        type : 'post',
        data : {},
        beforeSend : function(){
            //check if input is on focus
            if(input_focus !== true){
                //show the loading.gif, assume that #loader
                $("#loader").show();
            }else{
                //hide the loading.gif, assume that #loader
                $("#loader").hide();
            }
        },
        complete : function(){
            //when the ajax request is complete
        },
        success : function(response){
            //the response function
        }
    });
    

Related Articles