Code Monkey home page Code Monkey logo

font-picker's Introduction

Font Picker

A simple, customizable font picker allowing users to preview, select and use Google Fonts on your website.

  • Simple setup
  • No dependencies
  • Automatic font download and generation of the required CSS selectors
  • Efficient font previews (full fonts are only downloaded on selection)

Demo

If you use React, see Font Picker for React.

Font picker demo

Getting started

To be able to access the API, you'll need to generate a Google Fonts API key.

1. Setup

You have the following options for installing/using the package:

  • Using script tags: Download the FontPicker.js file from the releases page and save it in your project. Include the script in your HTML at the end of the document <body>:
<script src="path/to/FontPicker.js"></script>
<script>
	const fontPicker = new FontPicker(
		YOUR_API_KEY, // Google API key
		"Open Sans", // Default font
		{ limit: 30 }, // Additional options
	);
</script>
  • Using NPM: If you're using a module bundler like Webpack, you can install the font-picker package using NPM and import it in your code:
npm install font-picker
import FontPicker from "font-picker";

const fontPicker = new FontPicker(
	YOUR_API_KEY, // Google API key
	"Open Sans", // Default font
	{ limit: 30 }, // Additional options
);

2. Displaying the font picker

Create an empty <div> with id="font-picker" in your HTML file. This is where the font picker will be generated.

<div id="font-picker"></div>

3. Applying the selected font

Add the class "apply-font" to all HTML elements you want to apply the selected font to.

When the user selects a font, it will automatically be downloaded and applied to all HTML elements with the "apply-font" class.

Class names

Customization

Parameters

The following parameters can be passed to the constructor of the FontPicker class:

const fontPicker = new FontPicker(apiKey, defaultFamily, options, onChange);
  • apiKey (required): Google API key
  • defaultFamily: Font that is selected on initialization. Default: "Open Sans"
  • options: Object with additional optional parameters:
    • pickerId: If you have multiple font pickers on your site, you need to give them unique IDs which must be appended to the pickers' id attributes and the .apply-font class names. Example: If the options object is { pickerId: "main" }, use #font-picker-main and .apply-font-main
    • families: If only specific fonts shall appear in the list, specify their names in an array. Default: All font families
    • categories: Array of font categories to include in the list. Possible values: "sans-serif", "serif", "display", "handwriting", "monospace". Default: All categories
    • scripts: Array of scripts which the fonts must include and which will be downloaded on font selection. Default: ["latin"]. Example: ["latin", "greek", "hebrew"] (see all possible values)
    • variants: Array of variants which the fonts must include and which will be downloaded on font selection. Default: ["regular"]. Example: ["regular", "italic", "700", "700italic"] (see all possible values)
    • filter: Function which must evaluate to true for a font to be included in the list. Default: font => true. Example: If font => font.family.toLowerCase().startsWith("m"), only fonts whose names begin with "M" will be in the list
    • limit: Maximum number of fonts to display in the list (the least popular fonts will be omitted). Default: 50
    • sort: Sorting attribute for the font list. Possible values: "alphabet", "popularity". Default: "alphabet"
  • onChange: Function to execute whenever the active font is changed

Functions

The FontPicker class exposes the following functions:

  • getFonts(): Returns a map of all font names/objects
  • addFont(fontFamily: string, index?: number): Adds the specified font to the font list (at the given index)
  • removeFont(fontFamily: string): Removes the specified font from the font list
  • getActiveFont(): Returns the font object of the currently active font
  • setActiveFont(fontFamily: string): Sets the provided font as the active font
  • setOnChange(onChange: (font: Font) => void): Update the onChange function after the font picker has been initialized

Development

Requirements: Node.js, Yarn

  1. Clone this repository: git clone REPO_URL
  2. Install all dependencies: yarn
  3. Generate the library bundle: yarn start
  4. View the rendered component on localhost:3000

Suggestions and contributions are always welcome! Please discuss larger changes via issue before submitting a pull request.

font-picker's People

Contributors

dependabot[bot] avatar samuelmeuli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

font-picker's Issues

Option to reset the picker font back to default

Hi there,

I just wanted to ask is there an option to reset the picker font back to the default font? I've gone over the documentation and I can't personally find anything, but I could be missing it. If not, is there any way to implement this kind of feature?

Option to configure colors

Is there an option to configure the background colors of the menu component? Had a look at the source and it seems hardcoded in css string. Any way to bring it to options to make it configurable?

Fonts from custom URL

Hi,
got a question that I can't even believe myself. I found that according to https://en.m.wikipedia.org/wiki/Google_Fonts

Webmasters within Germany have received warning letters from lawyers claiming that loading Google Fonts directly from Google servers was not GDPR compliant.

According to some German sources the webmasters were even asked to pay for the warning letters.

Is there an offline mode with which to load the fonts locally to avoid potential violations of EU GDPR law?

Thanks a lot a man - really love the picker!
Cheers Tom

Option keys aren't optional with TypeScript

export interface Options {
    pickerId?: string;
    families?: string[];
    categories?: Category[];
    scripts?: Script[];
    variants?: Variant[];
    filter?: (font: Font) => boolean;
    limit?: number;
    sort?: SortOption;
}

it would be better to set options to nullable, because it complains when using the module in typescript
image

Missing Characters

Hi!

Im using this awesome font picker, but Im having trouble with some standard characters.

Example: The Uppercase X doesnt work, but the lower case does work:
Screenshot (85)
In GoogleFonts you can see that the characters are supported:
Screenshot (86)

I miss those characters both in the preview and then using them in the project.

What do you think I need to look for?

onChange event is sent before the font is loaded

Hey @samuelmeuli ,
Thanks for the great tool, very useful !
I am trying to use it in a demo with a canvas, so the onChange event seems perfect to re-render the canvas after the font is changed.
But that does not work as the event is fired before the font is fetched.

I have tried to dig in the code if it is expected behavior or issue.

The code here feels like the event should be fired after font is loaded:
https://github.com/samuelmeuli/font-manager/blob/fd522c973b06903e59b9fe756727100d993c8dad/src/FontManager.ts#L182
But inside that function, loading is not made async:
https://github.com/samuelmeuli/font-manager/blob/b11dce5cda750a2619e37581d3f2b2d19eefd010/src/loadFonts.ts#L79

What's your thoughts on this ?
Thank you!
Emmanuel

Font loaded callback

Hello
Thanks for the font-picker, it works pretty nice but I have the following issue:

Currently the onChange function will trigger after the font were selected - but BEFORE it were loaded and actually applied.

I need the callback on when the font is loaded since I'm using fonts with canvas text - and those require manual update to be properly redrawn.

Feature request: Search by name

Hi,

it would be great if we can search in Google Fonts library for font by its name. Like, the picker has an input for search, and when I type in something, it will returns all the font including that string.

Thanks.

How to removed font families onload

I'm trying to remove a bunch of font families, Hind Siliguri, Hind Madurai, Mukta, Noto Sans HK, Noto Sans JP, and more.

Are there any examples I can remove them onload?

I can use removeFont onChange, but not onload.

Also adding the removeFont method to the onChange callback, it fires errors when I select a font since it is already removed.

image

const fontPicker = new FontPicker(
	"My-API-Key", // Google API key
	"Open Sans", // Default font
	{ limit: 100 }, // Additional options
	()=>{
	    const fontsToRemove =['Hind Siliguri', 'Hind Madurai','Mukta','Noto Sans HK','Noto Sans JP','Noto Sans KR','Noto Sans SC','Noto Sans TC','Noto Serif JP','Assistant','Mulish','Padauk', 'Cormorant Garamond']
	    fontsToRemove.forEach(font => {
	    fontPicker.removeFont(font)
	});			
    }
);

caching

Hello,

Loving your script, thanks. Is there a way to add some caching the google web fonts requests so it uses fewer api calls (e.g. a local JSON file etc)?

Set "Not selected"

Hello. How can I set "Not selected" row?
For example i want to allow for user "reset" the font setting. The row with empty value.

`font-manager` dependency not found

I used the following code:

<div id="font-picker"></div>
const fontPicker = new FontPicker(GOOGLE_API_KEY, "Open Sans", {
    limit: 30
  });

I also tried specifying the pickerId:

<div id="font-picker-bodytext"></div>
const bodyTextFontPicker = new FontPicker(
    GOOGLE_API_KEY,
    "Open Sans",
    {
      pickerId: "bodytext",
      limit: 25
    }
  );

But I get the following error:

Cannot read property 'OPTIONS_DEFAULTS' of undefined  at new FontPicker

I included the FontPicker.js from the dist folder.

Document not defined

Font-picker is used as a dependency in react-font-picker. Building the project fails due to document not being defined at build time. You need to wrap lines 158-159 of index.es.js as

if(typeof document !== 'undefined'){
    var previewFontsStylesheet = document.createElement("style");
    document.head.appendChild(previewFontsStylesheet);
}

Cannot resolve dependency 'font-picker' in 3.02

When I try and run my project using parceljs (which worked with font-picker 2.x) i get this error 'Cannot resolve dependency 'font-picker''

Not sure whats causing it but I took a look at the package.json in node_modules and these paths dont seem to exist:

  "main": "dist/font-picker/FontPicker.js",
  "module": "dist/font-picker/FontPicker.es.js",

Calling `setActiveFont` after constructor does not work

Hello. Is it correct? When after init of fontPicker I try to set font:

const fontPicker = new FontPicker(
    YOUR_API_KEY, // Google API key
    "Open Sans", // Default font
    { limit: 30 }, // Additional options
  );

fontPicker.setActiveFont("Ubuntu");

I get this:

FontPicker.js:1 Uncaught TypeError: Cannot read property 'classList' of undefined at t.value (FontPicker.js:1)

Google Chrome (the last version) Version 76.0.3809.100 (Offizieller Build) (64-Bit)
p.s. Getter is works.

Preload or singleload fonts

Hello,

I am currently working on a project where many pieces of text can use different fonts thus instances of the Font picker can be constructed a lot time within my UI, requesting google fonts any time it happens.

Is there a way to request google fonts only once for any number of picker ?

Thanks.

Apply font doesn't work with multiple font pickers

Hi,

Thanks for a great library! I noticed that this line:

activeFontStylesheet.replaceChild(styleNode, activeFontStylesheet.childNodes[0]);

Always replaces the whole style. This unfortunately leads to that two different font pickers will overwrite each others styles. So only one font can be applied at once. I guess its possible to work around by just using inline styles, but it would of course be easier wil the apply-font class.

fontpicker

TypeError: _this2.onChange is not a function

Hello,

I am trying to implement the lib on a Rails app, with the purpose of being able to select a font in an admin panel to use it later on the front.
My idea is to call another function with onChange to get the value of the selected font and add it to a hidden input in my form, in order to save it to the database

Currently doing simple test, I noticed an error on onChange

Here is what I got so far :

import FontPicker from "font-picker/dist/FontPicker.js";

$(document).on('turbolinks:load', function() {

  const fontPickerTitle = new FontPicker(
    'xxxxxxxxxxxxxxxx',
    "Ubuntu",
    { pickerId: "title" },
    { onChange: console.log('test') }
  );

})

On first load, the console.log('test') works correctly.
But when I select another font in the dropdown, I got the following error :

TypeError: _this2.onChange is not a function

Maybe this is due to Rails turbolinks, but I didn't find another way than wrapping the const into on('turbolinks:load', function(), otherwise it does not find the markup with the ID of the div font-picker-title.

Any clue on what is going on ?

Thanks!

Standard fonts

Hello. I would like to ask how to add the standard fonts as Times New Roma, Tahoma etc?

fontPicker.addFont('Arial'); this is works.
fontPicker.addFont('Tahoma'); doesnt work
fontPicker.addFont('Helvetica'); doesnt work

onChange only fires once during initialization

Hey Samuel and friends... My expectation of the below is that foo() will execute each time the active font is changed. In other words, the onChange function of the constructor should fire every time a user selects a new font. However, it seems foo() is only executed once on initialization.

let fontPicker = new FontPicker(
    'keysdgjlkjsdg', // Google API key
    'Open Sans', // default font
    {limit: 20},
    foo()
);    

function foo() {
    console.log ('font changed')
}

Let me know if you'd like a fiddle.

Webpack and Array.from(fontMap.values());

I'm using the same bundle in two different environments(testing which is a copy of the full website and local which is just the necessary parts to launch the same) and for some weird reason font-picker works fine on local and doesn't work on testing - it doesn't generate the dropdown list properly.

I've checker everything through headers to response and I've debugged to one simple conclusion - this link is generated wrongly:
https://fonts.googleapis.com/css?family=&subset=latin&text=&font-display=swap
since it should look like this
https://fonts.googleapis.com/css?family=Roboto%3Aregular%7CLato%3Aregular%7CMontserrat%3Aregular%7CRoboto+Condensed%3Aregular%7CSource+Sans+Pro%3Aregular%7COswald%3Aregular%7CRaleway%3Aregular%7CRoboto+Mono%3Aregular%7CMerriweather%3Aregular%7CRoboto+Slab%3Aregular%7CPoppins%3Aregular%7CNoto+Sans%3Aregular%7CPT+Sans%3Aregular%7CUbuntu%3Aregular%7CPlayfair+Display%3Aregular%7CMuli%3Aregular%7CPT+Serif%3Aregular%7CLora%3Aregular%7CSlabo+27px%3Aregular%7CTitillium+Web%3Aregular%7CNunito%3Aregular%7CFira+Sans%3Aregular%7CNoto+Serif%3Aregular%7CRubik%3Aregular%7CWork+Sans%3Aregular%7CNanum+Gothic%3Aregular%7CNoto+Sans+JP%3Aregular%7CInconsolata%3Aregular%7CQuicksand%3Aregular&subset=latin&text=RobtLaMnser+CdSucPOwlyihpNTUfD27xmWFkGJIQ&font-display=swap

Since I didn't saw any changes on the previous response - I've dug into JS
And do you have any idea why with the same fontMap input produces different results with Array.from(fontMap.values());?
testing:
fonts_empty

and here is the local:
fonts_full

I'm using webpack and babel. It is super-weird that same bundle works differently in different environments.

I had issues with Map and Webpack previously.

Any advice on why this happens?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.