4

I'm trying to load a gif loader when I start to type in a textbox. I'm appending it to the div that contains the textbox on keyup. The problem I have is that the loader is appended every time I type a letter while I would like to append it only once when I type the first letter.

function loader(){

    $('#contrib_search').bind('keyup', function(){
        $('#contrib_text').append('<div id="loader"></div>');
    });
}

Any idea how to do this?
Thanks

Mauro74
  • 4,686
  • 15
  • 58
  • 80

4 Answers4

4

Using 'one' could help:

function loader() {
  $('#contrib_search').one('keyup', function () {
    $('#contrib_text').append('<div id="loader"></div>');
  });
}
Angel M.
  • 2,692
  • 2
  • 32
  • 43
3

you can unbind the keyup after you add the loader

function loader(){

    $('#contrib_search').bind('keyup', function(){
        $('#contrib_text').append('<div id="loader"></div>');
        $('#contrib_search').unbind('keyup');  //or $(this).unbind probably a tad faster
    });
}
Rodolfo
  • 4,155
  • 23
  • 38
2

My advice is to hardcode loader into your HTML code and then .show() it on .keyup() event handler.

Then for example in .blur() event .hide() it and the problem is gone.

Edit:

var $contrib = $('#contrib_text');

$contrib.bind({
    keyup: function(){
       $contrib.find("#loader").show();
    },
    blur: function(){
       $contrib.find("#loader").hide();
    }
});
avall
  • 2,025
  • 2
  • 16
  • 28
2

Maybe this could work :

var pressed = false;
    function loader(){

        $('#contrib_search').bind('keyup', function(){
            if (pressed == false ){
                $('#contrib_text').append('<div id="loader"></div>');
                pressed = true;
            }
        });
    }

or instead of using this boolean just call unbind instead of my line saying pressed = true;

user1374021
  • 196
  • 1
  • 9