Automattic / Iris

A(n awesome) Color Picker
GNU General Public License v2.0
259 stars 67 forks source link

Accept function as parameter to "target" option #63

Open masonhale opened 6 years ago

masonhale commented 6 years ago

Adds support for specifying a function as the argument to "target" initialization option, to enable dynamic positioning relative to the input element.

This is especially important when more than one color picker is embedded on a single page, and where individual initialization of each color picker element (in order to bind the target to a known element id, for example) is undesirable or unfeasible (for example if the color picker input code is dynamically generated).

Example usage:

<html>
<head>
<!-- load jquery, jquery-ui, iris here -->
<style>
.color-picker-wrapper {
   position: absolute;
   z-index: 999;
   display: inline-block;
}
.color-chip {
   display: inline-block;
   height: 20px;
   width: 20px;
}
</style>
</head>
<body>

<div class="input-wrapper">
   <input type="text" class="color-picker"  name="primary-color">
   <span class="color-chip"></span>
   <span class="color-picker-wrapper"></span>
</div>
<div class="input-wrapper">
   <input type="text" class="color-picker"  name="secondary-color">
   <span class="color-chip"></span>
   <span class="color-picker-wrapper"></span>
</div>

<script language="javascript">
jQuery(document).ready(function($){
    // configure iris color picker
    $('.color-picker').iris({
      change: function() {
        var $this = $(this);
        $this.parent().find('.color-chip').css('background-color', $this.iris('color'));
      },
      // NOTE: relies on change to Iris library to accept function for 'target' option
      target: function(elem) {
        var x = $(elem).parent().find(".color-picker-wrapper").first();
        return x;
      }    
});
</script>
</body>
</html>

In the example above, the color picker will be appended to the span with the class "color-picker-wrapper" located within the same containing div as the input element (with class "color-picker").