Search code examples
jquerytwitter-bootstrappopovercolor-picker

Using farbtastic colorpicker in Twitter Bootstrap's popovers


In a user interface based on Twitter Bootstrap I have multiple buttons that should trigger a popover yielding a farbtastic colorpicker. At the moment I have attached it to the <body /> tag and delegated it to the buttons:

HTML

<div id="body" style="text-align:center;">

<a class="btn" rel="popover">First</a>
<a class="btn" rel="popover">Second</a>

<div id="colorpicker">
    <input type="color" id="color" />
    <div class="my-farbtastic"></div>
</div>

</div>

JavaScript

$(document).ready(function() {
    $("body").popover({
        trigger: "click",
        placement: "bottom",
        title: "Colorpicker",
        content: $("#colorpicker"),
        selector: "a[rel=popover]",
        html: true
    }).on("click", "a[rel=popover]", function() {
        $("#colorpicker").find(".my-farbtastic").farbtastic("#color");
    });
});

With this approach I have two problems:

  • The popover does not appear next to the respective button, but is aligned with the <body /> tag.
  • The colorpicker only works when the popover is triggered for the first time. Afterwards all JavaScript-based functionality is lost.

See this jsFiddle for a live demo.

Thank you in advance for any helpful thoughts on that!


Solution

  • In between I solved the problem myself and this is what my solution looks like (also see version 11 of the jsFiddle):

    HTML

    <div id="body" style="text-align:center;">
        <input type="text" rel="colorpicker" data-tool="first" />
        <input type="text" rel="colorpicker" data-tool="second" />
    </div>
    

    JavaScript

    $(document).ready(function() {
        $("input[rel=colorpicker]").each(function(i, input) {
            $this = $(input);
            return $this.popover({
                title: "Colorpicker <i class='icon-remove pull-right'></i>",
                trigger: "click",
                placement: "bottom",
                html: true,
                content: "<div id='colorpicker-" + $this.data("tool") + "'>"
                + "<div class='color-picker'></div>"
                + "</div>"
            }).on("click", function() {
                $this = $(this);
                $target = $("#colorpicker-" + $this.data("tool"));
                $target.find(".color-picker").farbtastic(function(color) {
                    $this.val(color).css("background-color", color);
                });
            });
        });
    });