JQuery: Techniques for accessing the assigned font of an element

Can the assigned font of an element be retrieved using jQuery?

For example, if there is this CSS:

#element
{
font-family: blahblah,Arial;
}

In the above case, the Arial font will be assigned to #element. Is it possible to extract that information using JS/jQuery?

Is something like this feasible:

$('#element').css('font-family');

which would return only blahblah,Arial;

Answer №1

(function($) {
    $.fn.findFont = function() {
        var fontsUsed = $(this).css('font-family').split(",");
        if ( fontsUsed.length == 1 )
            return fontsUsed[0];

        var selectedElement = $(this);
        var detectedTypeface = null;
        fontsUsed.forEach( function( font ) {
            var duplicate = selectedElement.clone().css({'visibility': 'hidden', 'font-family': font}).appendTo('body');
            if ( selectedElement.width() == duplicate.width() )
                detectedTypeface = font;
            duplicate.remove();
        });

       return detectedTypeface;
    }
})(jQuery);

update: removed the duplicated item from the document.

Just created this now, again, it depends on element width - so results may vary.

$('#element').findFont(); //displays Times New Roman

Answer №2

Utilize the Detector library for this task:

Because the browser selects the first available font from the list, it's important to review the list of fonts and confirm if you have that specific font installed on your system.

Below is the JS/JQuery code snippet:

$(function() {
    var detectFont = function(fonts) {
        var detective = new Detector(), i;
        for (i = 0; i < fonts.length; ++i) {
           if (detective.detect(fonts[i]) !== true) {
               continue
           }
           return fonts[i];
        }    
    }
    var fonts = $('#abcde').css('font-family');
    fonts = fonts.split(',');
    console.log(detectFont(fonts));
});

Here is a live demo I've set up: http://jsfiddle.net/netme/pr7qb/1/

Hopefully, this method proves helpful for you.

Answer №3

Updated version of kmfk's solution that now works for all types of elements. Due to limitations with block elements having fixed or dynamic width, this implementation focuses on inline elements:

/**
 * Function to determine the font of an element by comparing font widths from the font-family css attribute
 * @link http://stackoverflow.com/questions/15664759/jquery-how-to-get-assigned-font-to-element
 */
(function($) {
    $.fn.detectFont = function() {
        var fontfamily = $(this).css('font-family');
        var fonts = fontfamily.split(',');
        if (fonts.length == 1)
            return fonts[0];

        var element = $(this);
        var detectedFont = null;
        fonts.forEach(function(font) {
            var clone = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': fontfamily, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
            var dummy = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': font, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
            
            if (clone.width() == dummy.width())
                detectedFont = font;
            clone.remove();
            dummy.remove();
        });

       return detectedFont;
    }
})(jQuery);

Answer №4

Change the font of an element with this jQuery code:

Give it a go.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Select values to Component from an array contained within an array of objects

Each user possesses a unique list of tags, and every item owned by the user can be associated with multiple tags from this list. In this scenario, I am attempting to display all the tags belonging to a user for a particular item. If the item has a tag tha ...

Sending information to a component through navigationPassing data to a component

When attempting to move from one component to another page using routes and needing to send parameters along with it, I have experimented with passing them as state through history.push(..) like the following code. However, it does not seem to be working a ...

What could be the reason for my CSS animation with :hover @keyframes not functioning?

As a newcomer, I am struggling to understand why this code isn't functioning correctly. My goal is to create the illusion of a flying bird. This is my HTML: <img src="http://dl.dropboxusercontent.com/u/105046436/tw.png" /> <br> <div c ...

What is the best way to include JavaScript in a web view within an Ionic Android application?

I'm in the process of incorporating a header bar into the web view for my app. Utilizing the cordova inAppBrowser plugin to achieve this, I tested using the following code: var win = window.open( URL, "_blank", 'location=yes' ); win.addEven ...

Tips for creating a seamless horizontal scrolling effect in Angular when hovering (automatically)

One of the components I'm working on features a gallery with an X axis orientation. <div class="gallery"> <div (mouseenter)="scrollTo('left', $event)" (mouseleave)="clearIntervalRepeater()" class="left"></div> < ...

What is the best way to arrange cards in a horizontal stack for easy carousel viewing later on

My main objective is to design a unique card carousel where users can navigate through the cards by clicking on arrows placed on the left and right sides. The approach I am considering involves stacking multiple card-decks and smoothly transitioning to th ...

What is the method for adjusting the input text color in a textarea to green?

Is there a way to change the input color for this textarea so I can type green text on a black background? textarea{ background-color: black; } <textarea id="htmlCode" class="1111" placeholder="HTML"></textarea> ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

Is the conditional module require within an "If" statement always executed in nuxt.config.js?

Despite the missing file mod.json, the "require" statement is still executed leading to an error. The condition should have prevented it from entering the "if" block: const a = 1; if(a === 2){ const mod = require('./scripts/mod ...

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this: <div ng-repeat="comment in comments"> <li class="item" ng-class-even="'even'"> <div class="row"> ...

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

Using a regular div to display a modal - Reactstrap

Exploring the possibilities with a Reactstrap Modal: Modal - Reactstrap I am curious about integrating this modal seamlessly into a page layout, similar to a regular div. For example, having the modal display on the page without the animation effects and ...

Are there equivalent npm variables like (`npm_config_`) available in yarn console scripts?

Utilizing variables in custom npm commands is possible (example taken from ): { "scripts": { "demo": "echo \"Hello $npm_config_first $npm_config_last\"" } } Can this functionality also be achieved ...

Unleashing the Power of Vuejs: Setting Values for Select Options

I have a specific requirement in my Vue application where I need to extract values from an XLS file and assign them to options within a select dropdown. Here is what I currently have: <tr v-for="header in fileHeaders" :key="header"&g ...

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...

Certain CSS styles for components are missing from the current build

After building my Vue/Nuxt app, I noticed that certain component styles are not being applied. In the DEVELOPMENT environment, the styles appear as expected. However, once deployed, they seem to disappear. All other component styles render properly. Dev ...