Import all icons to your website

2 Min. Read
Aug 14, 2019

We recently stumbled across a problem where we had to provide the user with a functionality of being able to set an icon for a certain form. Instead of just giving the user a choice to upload the icon svg, provide a link to the icon, or just choose amongst a handful of them, we decided to first create a database of all the available icons that we can choose from (fontawesome, in this case) and show those icons in a modal with integrated search functionality.

Here’s the list of all the icon names we’ve extracted and saved in a YAML file.

From then on it was straight forward task of displaying the icons in the modal

The steps include:

-First, parsing the icon names in the yml file

1
2
3
4
5
6
class Icons
  attr_accessor :data
  def initialize
    @data = Psych.load(File.read(Rails.root.join('app/controllers/concerns/icons.yml')))
  end
end

-Make it available to the view from controller

1
2
3
def new
@icons = Icon.new.data
end

-In the view page,

1
2
3
4
5
h1.icons-container
  .row id="iconWrap"
    - @icons["fontawesome"].each do |icon|
      .col-md-2.text-center.margin10bottom
        i [class = "#{icon} margin10all"]

-Some javascript to handle selection and search on icons

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
document.getElementById('iconSearch').addEventListener("keyup", function (e) {
      searchIcon(e.target.value);
  });

  function searchIcon(filter) {
      var wrap, iconName, txtValue;
      wrap = document.getElementById("iconWrap");
      iconName = wrap.querySelectorAll("i");
      for (let i = 0; i < iconName.length; i++) {
          txtValue = iconName[i].className.replace(' margin10all', '');
          if (txtValue.search(filter) > -1) {
              iconName[i].parentNode.style.display = "";
          } else {
              iconName[i].parentNode.style.display = "none";
          }
      }
  }

  document.querySelectorAll('i').forEach(icon => {
      var currentIcon = icon;
      icon.addEventListener('click', () => {
          handleClick(currentIcon);
      })
  });

  function handleClick(icon) {
      document.querySelectorAll('i').forEach(icon => {
          icon.parentNode.style.outline = "none"
      });
      icon.parentNode.style.outline = "1px solid red"
      document.querySelector('#iconPreview').setAttribute('class', icon.className);
      document.querySelector('#template_icon').value = icon.className.replace(' margin10all', '');
  }
  document.querySelector('#iconColor').addEventListener('change', () => {
      document.querySelector('#template_color').value = document.querySelector('#iconColor').value;
  });

As always, we hope you’ve learned something.