Search code examples
javascriptdomknockout.jsknockout-2.0knockout-mapping-plugin

Popup in Knockout.js relative to DOM element


I am trying to make a popup using the knockout js. But I am not able to get a popup relative to my dom element. I know that there are two solutions 1) $index to set to specific id. 2) You can also get the currently dom element via knockout too and don't use $index.

But I am unable to use the any of the above solutions. Anybody has a solution how can I have a popup like the image below for every foreach and relative to the current image.

Popup Template

ko.bindingHandlers.popover = {

 init: function(element, valueAccessor, allBindings, viewModel, bindingContext)
 {
    ko.bindingHandlers.value.init(element, valueAccessor, allBindings);
    var source = allBindings.get('popoverTitle');
    var sourceUnwrapped = ko.unwrap(source);
    $(element).attr('data-placement', 'bottom');
    $(element).popover({
      trigger: 'focus',
      content: valueAccessor(),
      title: sourceUnwrapped
    });
  },
  update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
    var value = valueAccessor();
    ko.bindingHandlers.value.update(element, valueAccessor);
  }
};
<div data-bind="foreach : list">
  <div class="col-lg-3 col-md-4 col-xs-6 thumb" >
     <a class="thumbnail ind" href="#">
      <img type="button" class="img-responsive" data-lightbox="" src="http://placehold.it/400x300" alt="" data-toggle="popover" data-bind="popover:" >
      </a>
  </div>


Solution

  • Assuming you're using the Bootstrap version of popover:

    I think the problem is with your focus based trigger. Image elements aren't focus-able by default. As for the position of the popover, it should already by relative to the element it's attached to so you shouldn't need to do anything fancy.

    After changing the trigger type it seems to work as I would expect.

    $(element).popover({
      trigger: 'hover',
      content: valueAccessor(),
      title: sourceUnwrapped
    });
    

    https://jsfiddle.net/3s2h7gz3/

    If you'd prefer to make the image element focusable you can give it a tabindex.

    <img tabindex="0" type="button" ...