Search code examples
javascriptjquerypopover

Jquery popover clone loses click event


i have one click event in page. after click one div is cloned. but after click "popover" appends on first div.

here is example i created: https://jsfiddle.net/stinky/d65swy7z/

after clone, popover only shows on first click.

i tried this

$('.click').on(function(){
  $(this).webuiPopover({url:'#popover-content'});
});

but not works.

this is popover plugin i use: https://github.com/sandywalker/webui-popover


Solution

  • There are a couple of issues with your code:

    1. $('.click').clone(true) applies the clone method to all the current existing .click nodes, but you only want it to clone 1 node, not all of them.
    2. $('#container').html($cln); would replace the entire contents of #container with one clone. What you want is to $('#container').html($cln);. In your case it happened to look like it was working because of the behavior explained above (all items were cloned, instead of just one).
    3. You need to clone without events otherwise, as you can see, all your clones copy the original, even in the position of the popover.
    4. As a result of the above, you need to register a new popover for your new clone (since you don`t want it to use the same popover as the original)
    5. Since your popover options specify a #popover-content id to use as content, the popover plugin seems to wrap/replace the node at that ID with the structure of the actual popover control. You will now have many elements using the same popover content, so you need to disable caching as described in the documentation https://github.com/sandywalker/webui-popover#default-options in order to be able to reuse that same content for all the popover instances.

    Here is the updated version of your code that works:

    var $target = $('.click');
    var popoverOptions = {
      url: '#popover-content',
      cache: false
    };
    
    $('.clone').on('click', function() {
      var $cln = $target.clone(false);
      $cln.appendTo($('#container'));
      $cln.webuiPopover(popoverOptions);
    });
    
    $target.webuiPopover(popoverOptions);
    <script src="https://cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.webui-popover/1.2.1/jquery.webui-popover.min.js"></script>
    <link href="https://cdn.jsdelivr.net/jquery.webui-popover/1.2.1/jquery.webui-popover.min.css" rel="stylesheet" />
    <a class="clone" href="javascript:void(0)">clone</a>
    <br>
    <br>
    <br>
    <a class="click" href="javascript:void(0)">click1</a>
    <div id="container"></div>
    <div id="popover-content" style="display: none;">
      HI!
    </div>