Skip to content
Advertisement

Programmatically get FontAwesome unicode value by name

Following the steps outlined in this answer, I am setting my cursor to a FontAwesome icon. Now, I would like to set the cursor to any icon, by class name (for example, fa-pencil). To accomplish this, it seems like I would need to be able to programmatically lookup the unicode value of a given icon.

I know that these values are listed in the font-awesome.css stylesheet, but I would like to avoid parsing that file, if another method exists.

Is this possible?

Advertisement

Answer

I have kludged together something that works:

var setCursor = function (icon) {
    var tempElement = document.createElement("i");
    tempElement.className = icon;
    document.body.appendChild(tempElement);
    var character = window.getComputedStyle(
        tempElement, ':before'
    ).getPropertyValue('content');
    tempElement.remove();
    
    var canvas = document.createElement("canvas");
    canvas.width = 24;
    canvas.height = 24;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#000000";
    ctx.font = "24px FontAwesome";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(character, 12, 12);
    var dataURL = canvas.toDataURL('image/png')
    $('body').css('cursor', 'url('+dataURL+'), auto');
}

This creates a temporary element with the given class, then uses window.getComputedStyle to grab the content of the :before pseudo-element.

Thank you everyone for all your help!

Advertisement