2

I am using the tooltipster jquery plugin to show title in a nicer way. In my site there is a link with two classes .fav tooltip

<div class="actsave">
    <a href="#" class="fav tooltip" title="Save">Save</a>
</div>

The .tooltip is use to take the above anchor title and display it according to the tooltipster plugin.

$('.tooltip').tooltipster();

This works just fine, but when a user will click on this link the entire DOM will be replace with a new DOM.

$("div.actsave").on("click", "a.fav", function(e){
    e.preventDefault();
    $(this).replaceWith('<a href="#" class="del tooltip" title="Delete">Delete</a>');
});

At this point no events are occurring with the new anchor with .del class. My question is how i can add a event listener to this newly created dom in jquery?

After doing some research i fix it this way:

$("div.actsave").on("mouseover mouseout", "a.del", function(e){
    $(e.target).tooltipster();
});

but it seems that we are adding same event again and again without any reason to the dom when we hover the link, so here is the question can we add an event listener to this newly created dom just for once?

rakibtg
  • 5,521
  • 11
  • 50
  • 73

2 Answers2

1
$("div.actsave").on("click", "a.fav", function(e){
    e.preventDefault();
    var newElement = $('<a href="#" class="del tooltip" title="Delete">Delete</a>');
    $(this).replaceWith(newElement);
    newElement.tooltipster();
});
bumpy
  • 2,002
  • 2
  • 14
  • 19
  • Yes, but it will look for all the links with the class `.del` but i am looking for only $(this) , Thanks – rakibtg Aug 15 '15 at 12:13
  • I see. You can maybe try creating the element prior to the call to replaceWith, so you have a reference to it. I updated my answer. – bumpy Aug 15 '15 at 12:26
  • Try to provide explanations instead of just code, it is usually a lot more helpful – xShirase Aug 15 '15 at 13:05
0

Create a flag to keep track using data()

$("div.actsave").on("mouseover mouseout", "a.del", function (e) {
    if (!$(this).data('triggered')) {
        $(e.target).tooltipster();
        $(e.target).data('triggered', true);
    }
});
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53