Adding Gradient Color To SVG Icons

Hi everyone,

I just wanted to raise the issue of whether it would be a good idea to add a feature where we could be able to add gradients to SVG icons. I have been looking for so many different solutions online and have not been able to find a possible solution and am still searching. I’m talking about the SVG icons with teh tags.

You can do it with a few lines of javascript

1 Like

If you want to add your icons from the components panel,
you can traverse the DOM and find all SVG elements with the specified data attributes

on the icon component add this attributes
data-gradient , data-stop1color="#d23939" and data-stop2color="hsl(60, 100%, 50%)"
Here are examples of valid color inputs for the stop1Color and stop2Color attributes

  • Hexadecimal: #ff0000, #f00
  • RGB: rgb(255, 0, 0)
  • RGBA: rgba(255, 0, 0, 0.5)
  • HSL: hsl(0, 100%, 50%)
  • HSLA: hsla(0, 100%, 50%, 0.5)

add this to a javascript file

document.addEventListener('DOMContentLoaded', () => {
  const applyGradientToSVG = (svgElement, index) => {
    const gradientId = `gradient-${index}`;
    const stop1Color = svgElement.getAttribute('data-stop1color') || '#d23939';
    const stop2Color = svgElement.getAttribute('data-stop2color') || '#bac62c';

    const gradientDef = `
      <defs>
        <linearGradient id="${gradientId}" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stop-color="${stop1Color}" />
          <stop offset="100%" stop-color="${stop2Color}" />
        </linearGradient>
      </defs>`;

    svgElement.innerHTML = gradientDef + svgElement.innerHTML;
    const paths = svgElement.querySelectorAll(
      'path, circle, rect, polygon, ellipse'
    );
    paths.forEach((path) => {
      path.setAttribute('fill', `url(#${gradientId})`);
    });
  };

  const svgs = document.querySelectorAll('svg[data-gradient]');

  svgs.forEach((svgElement, index) => {
    applyGradientToSVG(svgElement, index);
  });
});
2 Likes

I created a new JS file and copied the JS code above into that file, then I copied the attributes above and added them to the icon component but still there are no changes to the icon color. I was hoping that there could be a more simpler solution. But thanks for your input @kuligaposten. I appreciate it. :+1:t4: