3

I'm building a rails app and want the user to be able to choose a color at some point. To do this, I tried to implement a color picker in my form with the 'jquery-minicolors-rails' gem.

This question: How to add Colorpicker in Rails Active Admin? is pretty similar to what I want to do I guess but I couldn't make it work.

Here is what I tried:

I added gem 'jquery-minicolors-rails' in the Gemfile and ran bundle install.

app/frontend/packs/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("jquery")
require("jquery.minicolors")

require("./application.scss")
require("./application_front.js")
require("./application_back.js")


jQuery( function($) {
    $(".colorpicker").minicolors()
});

In this file, I added the lines containing jquery and jquery.minicolors as well as the $(".colorpicker").minicolors() snippet.

app/frontend/packs/application.scss

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

/*
 *= require jquery.minicolors
 */

.turbolinks-progress-bar {
  background-color: #3355c5;
}

Finally, my form:

<%= form_with(model: @my_model, local: true, html: {class: "form-group"}) do |f| %>
  <%= f.input :name, input_html: { class: 'colorpicker' } %>
  <%= f.submit("Confirm", id: "confirm_button") %>
<% end %>

Leaving f.input provokes an error when I reach that page undefined method 'input' for ... so I tried replacing with f.text_field for example but I just get a simple text field, I can't manage to make the color picker appear on this page.

I'm using Rails 6.0.2.1 and Ruby 2.6.3

Thanks for your help.

If you have any other means to add a color picker, feel free to tell me, I'm not attached to jquery-minicolors gem.

victorfink
  • 343
  • 4
  • 17

1 Answers1

1

If you are not attached to that package then you can try the one provided by html instead. See this example from w3schools for the usage:

https://www.w3schools.com/tags/att_input_type_color.asp

Prabin Poudel
  • 244
  • 3
  • 15
  • 1
    Thanks, it works. For information, I used: `<%= f.color_field :favorite_color, value: '#FFFFFF' %>`. However, I don't know how to allow the user to change the opacity of the color yet. Do you know how I could do it? Or maybe this deserves another question? – victorfink Apr 10 '20 at 15:21
  • I don't think it is possible to edit it to that extent with html color type. You can view these links for the help: - https://stackoverflow.com/questions/40280110/how-to-add-transparency-to-a-value-from-a-html-input-type-color-field-in-css - https://github.com/w3c/html/issues/1422 – Prabin Poudel Apr 10 '20 at 15:30
  • you could simply add img { opacity: 0.5; } with opacity as a decimal field and add an inline style – Jeremy Bray Jan 27 '21 at 21:00