Search code examples
javascriptjquerycssjquery-uispectrumjs

Make width not relative to parent


I implemented spectrum color picker, and I want to add the color picker to a draggable element. (I implemented the draggable element through JQuery UI.) This way, when you drag the draggable element, the color picker will go along with it.

I was able to implement that with appendTo: "parent", in the color pickers setting. Now I have another problem. The color picker has 2 main things. 1 - it has a predefined color palette. 2 - It has an a color picker where you can select custom colors.

Say the parent element is 200px (the draggable element). Since the color picker is now a child of the parent element, the color picker will try to size its width according to the parent element. The result is, the color picker goes beneath the predefined color palette. Which is not the default look.

How can I get the color picker container to have its own width, and not depend on a parent width?

JSFiddle

(Make the width of #wrapper to 500px to see the default appearance.)

$("#wrapper").draggable();


$("#colorPicker").spectrum({
  appendTo: "parent",
  showPalette: true,
});
#wrapper {
  width: 200px; /* Try Making this to 500px to see the default appearance.*/
  height: 100px;
  border: 1px solid grey;
  text-align: center;
}
#colorPicker {
  background-color: pink;
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">

<script src="http://bgrins.github.io/spectrum/spectrum.js"></script>
<link href="http://bgrins.github.io/spectrum/spectrum.css" rel="stylesheet" />



<div id="wrapper">Drag Me
  <div id="colorPicker">
    Click Me
  </div>
</div>


Solution

  • Take a look at the spectrum documentation.

    There is an "appendTo" property you can use to change which element the color picker is relative to.

    $("#droppable").spectrum({
      appendTo: "body",
      showPalette: true,
      showSelectionPalette: true,
    });
    

    this will create the side-by-side view you might be looking for.

    Since you want the color picker to drag with the wrapper, and be positioned relative, try the following style rule on the element bound to the spectrum handler:

    <div id="wrapper" style="overflow: visible;"> Drag Me
      <div style="position: relative; width: 500px;">
          <div id="colorPicker" style="width:200px;">
              Click Me
          </div>
      </div>
    </div>
    

    and keep your JS as it was.