jeudi 30 juin 2016

Delegate JQuery Popover Trigger Event (Loading Dynamic Divs in Rails)


I am using this rails popover gem and dynamically loading $(".trigger") divs as the user scrolls down. The trigger divs need to show a popover when clicked.

I have an onLoadFunction:

function OnloadFunction (){
   # stuff can get called here
}

and my DOM Ready function:

$(function(){    
    OnloadFunction();
    # Other stuff called here
});

Here's the popover code:

      $('.trigger').popover({
          my: 'center top', // of popover
          at: 'center top', // of trigger
        }).on('click', function() {
            console.log('World!');
        });

The DOM ready function only gets called once. But the OnLoadFunction gets called any time new objects are loaded. So if I add the popover code to the OnLoadFunction, it gets called multiple times and leads to unexpected behavior (popup shows, and then hides since it's being called twice).

If I add the popover code to the OnReady function, then my freshly rendered .trigger divs don't show the popover.

Ideally I would like to bind the popover event to the .body within my DOM ready function, but I'm not sure how to write that.. Any ideas? Something like:

$('body').on("click", ".trigger", function(){
          popover({
            my: 'center top', // of popover
            at: 'center top', // of trigger
          })
        });

But I just get "popover is not a function".


Aucun commentaire:

Enregistrer un commentaire