Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding jQuery slider in Bootstrap popover

I'm trying to put this code to work in rails:

$(elem).popover({
  title:"Brake activity",
  content: $("<div>").append( $("#slider").slider({ 
    range: "max",
    max: maxValue,
    min: maxValue / 5,
    value: maxValue / 2}) ).eq(0).outerHTML(),
  trigger: "manual"});

Almost everything goes fine, but the slider does no work -- it seems to be disabled. Even if I define the option disabled to false, I got the same result. The method outerHTML() was extracted from Get selected element's outer HTML.

I uploaded a screenshot showing how the slider appears: http://i48.tinypic.com/24azpkm.png

like image 928
user1588995 Avatar asked Aug 10 '12 00:08

user1588995


1 Answers

Possible Issues

First, any values you assign to the content property will get wrapped in a <p> element when rendered in the popover. I suspect that might be creating problems with the slider.

Second, unlike other Bootstrap components (such as Modal), the content in the Popover is not persistent, but rather is rendered on the fly. So, you're going to have an issue being able to persist values in your slider, given the way you've indicated thus far.

A Solution

One possible approach would be to attach and detach the content (in this case a slider) whenever the popover is shown or hidden. Unfortunately, Popovers do not trigger events, so you have to manage this manually.

First instantiate the slider that you will use, and keep it in the scope where you'll be handling the toggling of the popover:

var $slider = $('<div>').slider({
  range: "max",
  max: maxValue,
  min: maxValue / 5,
  value: maxValue / 2
});

Immediately after the popover is shown, you could attach the slider using:

$('.popover-content')
  .empty()
  .append($slider);

Note: If you have multiple popovers open at once, a more specific selector must be used.

Before hiding the popover, you would detach the slider manually:

$slider.detach();

This will take it off the DOM, but all it's data will persist.

I did up a demo that does this using a toggle button to trigger the popover. Note that the popover is initialized first (without being shown) and no initial value is given for content.

JSFiddle

like image 58
merv Avatar answered Nov 05 '22 06:11

merv