jQuery: Append once and stop (worked in older versions)

2.7k views Asked by At

So here's the code I'm using:

$(function(){
    $('<div id="info" style="width:auto; height:auto;"/>').load('test.php?var='+d+' #se', function() {
        $('#main').append(this);
    });
});
}

Now, when I trigger the function (with a keyup in a input box) the div loaded is appended over and over again on every keyup event.

I'm using jQuery 1.5 - in older versions, namely 1.2.6, the div wasn't appended after the first time and it worked fine (bug?).

How do I prevent the div from being appended over and over again? (disabling the "trigger" is not an option unfortunately.) I also tried appendTo, which is pretty much the same problem.

Someone help me please! Thanks a lot

2

There are 2 answers

1
Assad Nazar On

use

$(function(){
   if($("#info").length==0)
   {
      $('<div id="info" style="width:auto; height:auto;"/>').load('test.php?var='+d+' #se', function() {
        $('#main').append(this);
      });
   }
});
}

Assuming that "#info" is added dynamically.

0
mu is too short On

Sounds like you can use .one to bind your keyup handler:

$('whatever').one('keyup', function() {
    $('<div id="info" style="width:auto; height:auto;"/>').load('test.php?var='+d+' #se', function() {
        $('#main').append(this);
    });
});

The .one function acts just like .bind except that it unbinds itself after it executes once.