Search code examples
jqueryinsertafter

How do I use .one() handler correctly?


I want to insert a div element after a given element. How do I do it ONCE ?

This is what I have:

var i = 1;

$('<div id="plussign"></div>').one("insertAfter","#div" + i);

Solution

  • .one() is the same thing as .click() except it works only once and then detaches itself.

    You probably want to do this:

    var $target = $('#div' + i);
    
    if (!$target.next().hasClass('plussign')) {
      $('<div />', {'class': 'plussign'}).insertAfter($target);
    }
    

    Do note that I changed your id to a class. ids are unique and there cannot be two elements with the same id in the document. class, on the other hand, is not unique and can be used to group many elements together.