Code Monkey home page Code Monkey logo

lettering.js's Introduction

Lettering.js, a jQuery plugin for radical Web Typography

CDNJS

We developed a lightweight, easy to use Javascript span injector for radical Web Typography, we're calling it "lettering-jay-ess", and we're releasing it today for free over on Github. Let me demo it for you: </stevejobs>

Individual Letter Control with Lettering.js

We'll start with some really basic markup:

<h1 class="fancy_title">Some Title</h1>

After including jQuery 1.6.2+, download and include the minified version of Lettering.js, then a script block with the magical .lettering() method:

<script>
	  $(document).ready(function() {
	    $(".fancy_title").lettering();
	  });
</script>

The resulting code will churn your .fancy_title and output the following:

<h1 class="fancy_title">
  <span class="char1">S</span>
  <span class="char2">o</span>
  <span class="char3">m</span>
  <span class="char4">e</span>
  <span class="char5"></span>
  <span class="char6">T</span>
  <span class="char7">i</span>
  <span class="char8">t</span>
  <span class="char9">l</span>
  <span class="char10">e</span>
</h1>

Magical. Now the text is easy to manipulate in your CSS using an ordinal .char# pattern. This plugin assumes basic counting skills, but it's a pretty fast and easy way to get control over every letter.

Letters, words, lines, and more!

There you have it, but Lettering.js does even more! Lettering.js has the ability to split words and lines as well. If you want more information on how you can get radical with text, read the Lettering.js Wiki:

https://github.com/davatron5000/Lettering.js/wiki

Best Practices

We've found this to be a pretty quick and elegant solution to create typographical CSS3 posters. It's also a great solution for really custom type headings, while keeping the text selectable. Be smart and use sparingly. You'll probably break your browser if you try to wrap every letter on your page in a span tag, so don't do that. Look to use this in your Headings, Blockquotes, Asides, etc.

Kern Well

If you're going through the trouble to load a fancy font and that word or phrase is the largest on the site, then it's important for it to be kerned well. With Lettering.js, kerning is a breeze. You can simply use $("#id-of-what-i-want-to-kern").lettering(); and then on each .char#, you can set relative position or left/right margin. Works like a charm.

Accessibility

Lettering.js is now accessible by default. It uses an aria-label on the parent element and aria-hidden on each of the children to prevent screenreaders from pausing while reading each individual characters or words.

Non-Javascript Fallback

As with any kind of Javascript, have a fall back plan in case the user doesn't have javascript enabled. The bottom line is up to you, my bottom line would be "legible and on the screen". Also, use lettering.min.js Download the Minified Version of Lettering.js here

Performance Anti-Pattern

Web performance patterns advise that you put Javascripts at the bottom of your page before your </body> tag. There is an unfortunate side effect where you may experience a FOUT (Flash of Unstyled Text) when you're manipulating your text after the DOM has loaded. Unfortunately, we found the best solution to avoid/minimize the FOUT caused by this plugin is to put your scripts (jQuery, Lettering.js) in the document <head>. On the one hand, your page will load slower. On the other hand, a flash/restyling makes your site feel slow. Users might ultimately feel the site is faster if they don't see the FOUT.

Download, Fork, Commit, Please.

We really want Lettering.js to be a quality helper for web typography. If you have any feedback or suggestions, please leave those over on the Github. We're excited about typography on the web and want to help make it print quality.

lettering.js's People

Contributors

bassettsj avatar davatron5000 avatar jvgreenaway avatar nishigori avatar prayagverma avatar pvnr0082t avatar slexaxton 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  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

lettering.js's Issues

Change color in heading

Hi,

I just want to change first word color and style in heading neither whole heading or syntax I'm putting code.

<h1>Recent Projects</h1>

in this code I want to present {{{ Recent }}} in Red color and Projects iin black but i don't want to use span to separate the heading because when I want it should behave dynamically..

Regards
Mufasser

Unicode support

Fix for unicode support:
function injector(t, splitter, klass, after) {
var text = t.text(),
inject = '',
i = 0;
for (let char of text) { //this kind of iterator is unicode safe
inject += '' + char + '' + after;
i++;
}
t.attr('aria-label', text)
.empty()
.append(inject)
}
For more information: http://www.2ality.com/2015/01/es6-strings.html

Tabbing or spaces in mark up add extra spans - Bug? Maybe not

I'm not sure if this is a bug or not but it confused me for a good 10 minutes.

I've created a pen to highlight the problem I had: http://cdpn.io/petGF

Basically, I had my div set up with an id to target with lettering.js and inside the div I was using PHP to echo a value, I mistakenly added tabbing and went to a new line to make my code look nice and stuff but that seems to make lettering add extra spans.

Removing the tabs fixed it, as I said though I don't know if this is a bug or if I was just using it wrong.

Lettering.js interferes with existing elements inside title

All existing elements inside a title get removed, so when you have, for example, a fancy Baskerville-Italic ampersand inside a title, it gets killed by the script which ignores all elements inside it.

Example that breaks somewhat: <h1>Photos <em>&amp;</em> Videos</h1>

Double wrap 'lines'

Hello,

Is it possible to double wrap? For example when using $('h1').lettering('lines'); it would be great to have something like:

<span class="line1"><span>Line 1</span></span>
<span class="line2"><span>Line 2</span></span>

Thank you in advance!

How to make this work on a phpbb style?

I've tried everything that I can possible think of. Including just copying the js and html code examples given in the exmaple folder but none of it works on a phpbb style.

empty character disappear when display: inline-block

Hi,

I'm trying to animate the span created by the plugin (using css transform), in order to do that I have to convert each span into display: inline-block, unfortunately, empty characters disappears, and there is no more space between words. I tried to target those characters in css using :empty but the span is not really empty (there is an empty space). Am I missing something? can't really find answer to that.

Is it possible to add a class to those empty span?

image

image

Character Coloring

I have been trying to get a particular character to be colored but it doesn't seem to work, I cannot identify from CSS whether the spans contain the letter "A" or "B"

Feature: Adding the letter to the class

The plugin could be extended in the following way: To the char# class, add also a letter-X class, where X is the content of the span.

Example:

Current result:

<span class="char1">A</span>

Proposed result:

<span class="char1 letter-A">A</span>

Side effects: Whitespace must be addressed specially.

Advantages: In the CSS you could address all 'A's at once, like, e.g., doing baseline shifting.

Add a first and last class

It would be sweet if this added a class to the first and last letter for specific styling. :first-child would work, I suppose, but :last-child doesn't work until IE9

Undefined with jQuery 2.1

Does anyone have lettering work with more recent versions of jQuery? lettering.js is in the page, after jquery, but apparently undefined.

<a> missing when integrated into WordPress wp_nav_menu

Hi there,

I am have a navigation menu with links styled with lettering.js (a jQuery plugin).
On HTML / SASS works perfectly.

When I try to integrate that into WordPress everything's works well...a part from the tag is not wrapping anymore the nav links :( that's obviously a problem...what I do get is the that is created by lettering.js and of course my other styling, but no tags so can't really be used as a menu if you know what I mean...

Am I missing something ? Anyone with some kind of idea ? similar experience ?

Thanks,
Amit

Can you release a new version?

I found released v0.6.1 and v0.6 have not include bower.json, I use grunt-wiredep to inject files to HTML file automaticly which is defined in bower.json's main field. so grunt-wiredep requred the bower.json file.

Events

Hey,

are for the extension methods? I want to make something after he finished lettering, but I don´t find something on your documentation. I mean something like this:

$("#myelement").lettering('words', function() { // Text });

It's not working for me, wordpress

Properly called the script in my theme functions file, added this code to the header<script type="text/javascript"> $(document).ready(function() { $(".site-description").lettering(); }); </script>... site-description being the p class of my site tagline, and nothing is happening. :(
Thanks for any help.

Feature: character-specific dynamic lettering

Hi there,

I love this, but there's one kind of web typography control I always want that this doesn't yet quite support.

In programs like InDesign or Quark, we designers often set a rule for the kerning of particular letter pairs across a whole document. For example, I'm always adding grep styles to InDesign to widen the default kerning in Gill Sans for " W" (space W) and " T", because these are kerned so tightly it looks like a mistake where the space has been missed out.

It would be great to be able to do this with lettering.js. For example, if you have established that in <h2 class="subhead"> on the front page, "O" and "K" aren't kerned tightly enough, that will also be true on any other <h2 class="subhead"> element using the same style on any page. It's more efficient and better long term to write a rule that for any "K" which follows an "O" in a <h2 class="subhead">, than to manually check every heading of every page, count characters for every heading where K follows - and then do this all again each time the copywriters reword the headings.

What I'd love to see is, an 'advanced rules' mode triggered by passing in objects, that sets letter-level classes for specific pairings. This could then be expanded for things other than pairings. Here's what I imagine the input looking like:

$('h2.subhead').lettering( { 
  pairs: [{
     0: { 
      characters: [ 'O', 'D', 'P' ]
    },
     1: {
       characters: [ 'K','B','N','E' ],
       classes: ['medium-tight-kern']
    },
 }
 {
    0: {
       characters: [ ' ' ]
     },
    1: {
       characters: [ 'W, T, V, Y' ],
       classes: ['double-width-kern']
      }
    }
  ],
  individuals: [
    {
      characters: ["!", "?"],
      classes: ['heavy-punctuation', 'double-width-kern']
    },
    {
      characters: ["... "],
      classes: ["clean-ellipsis"]
    },
  ]
});

This would be processed to look through the element, and for any K, B, N or E that follows a O, D or P, it would apply a span with class 'medium-tight-kern', and for any W, T, V or Y that follows a space, it applies the class 'double-width-kern'. medium-tight-kern would be defined in css to use a negative margin to bring the upright of these characters closer to the curve of the preceding character, double-width-kern would increase the gap.

I added some example rules for individual characters or sets of characters as an example of how this feature could easily be expanded to support even more awesome.

If you'd like some inspiration on the sort of rules people apply to characters, pairs, etc in documents for print (and how awesome it would be to have this kind of power on the web) check out this great InDesign plugin and the example markup: http://www.kahrel.plus.com/indesign/kern.html

Function to filter which elements will be "lettered"

This would help optimize performance. For example, let's say I want to style the first word and first letter of every paragraph. Currently there's no other way apart from:

("p").lettering('words').children('span').lettering();

And then styling p .word1 and p .char1. That, of course, would create a pretty huge DOM if you have an amount of text in the page.

By adding an optional function parameter we can limit which caracters/lines/words are "lettered". The function should be passed the original text, the current caracter/line/word and its index in the sequence, and return a boolean saying whether you want it to be spanned or not.

function onlyfirst(phrase, element, index) {
      return (index == 0);
}

("p").lettering('words', onlyfirst).children('span').lettering(onlyfirst);

This would convert:

<p>Lorem ipsum...</p>

Into:

<p>
  <span class="word1">
    <span class="char1">L</span>orem
  </span> 
  ipsum...
</p>

This would allow also for automatic kerning correction of given letters or even letter groups along whole texts, and probably lots of other uses that now are forbidden due to the DOM growing excessively if you apply lettering to the entire page.

I know that your codebase is absolutely minimal but I think that this single addition is fairly simple and would add immense flexibility.

Wrong parsing when wrapping words with a version number (with a dot)

I'd like to wrap the following words : 2.5 october 2014
But it fails to wrap "2.5" alone as a word, and it gives me instead only two words : "2.5 october" and "2014".
Thanks for your help !
(I can achieve what I want by wrapping letters, but it would be nicer with words ;-))

No dependency

Is there any plans to offer this amazing library without the jQuery dependency? :)

Webpack usage

Do you all have any way to show how this is used with webpack? Be great to see this documented some place.

What's the point of slicing the arguments?

Is there a reason why (lines 58 & 60) you slice the arguments and pass them into the .apply? The arguments aren't used anywhere, and there's nothing in the documentation to suggest that they would ever be any additional ones passed in anyway.

So replacing lines 57 - 61 with the following should still work
if ( method && methods[method] ) {
return methods[ method ].apply( this );
} else if ( method === 'letters' || ! method ) {
return methods.init.apply( this ); // always pass an array
}

Or, in fact, if you just rename the "init" method to "letters", you could replace the whole lot with:

$.fn.lettering = function( method ) {
    try {
        return methods[ method || "letters" ].apply( this );
    } catche (e)  {
        $.error( 'Method ' + method + ' does not exist on jQuery.lettering' );
    }
    return this;
};

destroy()?

Any easy way to remove all spans? Essentially a "reset back to original markup" method?

typo in readme

Line 91: "You'll probably break your browser if you try to tried to do wrap [...]"

Span around spaces

Hi there,

Is there any way to stop the plugin from wrapping a span around any spaces in text?

Thanks,
Chris

Bower

It seems that the package has not being registered in Bower. I looked for either letteringjs and jquery-lettering but no results :(

<scripts> at bottom of page solution

An alternative to battle FOUT/C is using a 'no-js' class on the HTML tag, which is replaced by a 'js' when the page loads, like one found here:
http://html5boilerplate.com/

Then you can have a style to hide the fancy text initially.

.js #thingUsingFancyAssFont {
visibility: hidden;
}

then after your lettering.js code has run you can add a class to the body tag (say .letteringDone). Which then you use to bring back your hidden thing:

.js .letteingDone #thingUsingFancyAssFont {
visibility: visible;
}

You could include the class as an option of the plugin if you want to be nice, or people could do it themselves.

*Completely untested code, but I've done similar things. The concept should be there. ;)

Words with H1 tags

Hey guys, I could just be missing something here, but I'm trying to use the lettering words method with an H1 tag. It only is allowing me to manipulate each letter and not the whole word. I switched it to a paragraph tag and it works. I would rather have the site's main title in an H1 tag. Any suggestions?

I'm using this:

$(document).ready(function() {
$(".headline").lettering('words');
});

Not Working in Blogger

Hello Dear sir,

I just follow All the steps as you teach in your documentation, but still not working in blogger blog template. But when i check the same code in Dreamweaver that is working fine.

Please let me know how to resolve the issue or its not compatible with xml document?

Thanks & Regards..

code review from paul

i'll leave this as a ticket for funsies

i like the plugin idea. i def think we need it.
mostly for kerning and for that i think a sweeter API might be worth it.
i was thinking something like
.w1char3 so its easier to jump to a new word without counting all the letters
or
.w1firstk , .w4thirde

anyway. probably a 2.0 type thing but it was a thought..

code shit:

  • new Array() ==> []
  • create a common split() method or something so that init/words/lines all leverage it and you can make the code more DRY
  • hahaha i fucking love the md5 technique and comment
  • very much like whats going on in your $.fn.lettering definition. nice style.

structure shit:

  • you should probably build up your spans as a string and toss it into t all at once.. instead of appending inside a loop. it'll be much faster and far fewer reflows.

good work

Accessibility improvements

Lettering.js is inaccessible due to screen readers pausing at every HTML tag, including inline span tags.

A possible fix might be something along the lines of:

// See if aria-hidden has been set
if($(this).parents('[aria-hidden="true"]').length === 0) {
  // make a clone
  var clone = $(this).clone();
  // aria hide it
  clone.attr('aria-hidden',true);
  // visiually hide the clone
  clone.css({
    'position':'absolute',
    'left':'-10000px',
    'top':'auto',
    'width':'1px',
    'height':'1px',
    'overflow':'hidden'
  });
  // append the clone
  $(this).after(clone);

  // Do lettering stuff
}

Haven't tested it in case some one wants to pick it up. The screen reader should skip over the aria-hidden and read the clone.

`"xxx".split('')` can't get the whole character

For example

image

Gist: https://gist.github.com/hxgdzyuyi/07253960a46182ea56d2

Result:

image

First character is missing. "".split('') would broken when the string contains characters that are not in the Basic Multi-lingual Plane(bmp).

The correct javascript's function is:

Copy from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt#Example.3A_Getting_whole_characters

var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i=0, chr; i < str.length; i++) {
  if ((chr = getWholeChar(str, i)) === false) {
    continue;
  } // Adapt this line at the top of each loop, passing in the whole string and
    // the current iteration and returning a variable to represent the 
    // individual character

  alert(chr);
}

function getWholeChar (str, i) {
  var code = str.charCodeAt(i);     

  if (isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return str.charAt(i);
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) { 
    if (str.length <= (i+1))  {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i+1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return str.charAt(i)+str.charAt(i+1);
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i-1);

  // (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 > prev || prev > 0xDBFF) { 
    throw 'Low surrogate without preceding high surrogate';
  }
  // We can pass over low surrogates now as the second component
  // in a pair which we have already processed
  return false; 
}

Feature: Wrap all letters in a specific class

This is an awesome plugin, it's exactly what I need and has great performance.

The only issue for my use case, is that I want every letter to have a span, rather than class="char4".

Example:

<!-- Current -->
<span class="char1" aria-hidden="true">C</span>
<span class="char2" aria-hidden="true">O</span>
<span class="char3" aria-hidden="true">N</span>
<span class="char4" aria-hidden="true">T</span>
<span class="char5" aria-hidden="true">E</span>
<span class="char6" aria-hidden="true">N</span>
<span class="char7" aria-hidden="true">T</span>
<span class="char8" aria-hidden="true">S</span>

<!-- Is this possible? (Each letter has a specific class) -->
<!-- Notice: 'char-t' is being used twice  -->
<span class="char-c" aria-hidden="true">C</span>
<span class="char-o" aria-hidden="true">O</span>
<span class="char-n" aria-hidden="true">N</span>
<span class="char-t" aria-hidden="true">T</span>
<span class="char-e" aria-hidden="true">E</span>
<span class="char-n" aria-hidden="true">N</span>
<span class="char-t" aria-hidden="true">T</span>
<span class="char-s" aria-hidden="true">S</span>

So all the letter is lowercased, then added a class that we can style that individual letter with?

I managed to do this via: (to fit my needs for now).. but could be a useful plugin feature seeing as there is no other libraries that do this.

    // Within jquery.letter.js line 20
    inject += '<span class="'+klass+(item)+'" aria-hidden="true">'+item+'</span>'+after;

Reverse numbering?

Would it be possible to get this to number the spans in reverse order?

Is there an option for using actual words as class names?

For example, instead of having this result:

<span class="word1">Lorem</span> <span class="word2">ipsum</span> <span class="word3">dolor</span> <span class="word4">sit</span> <span class="word5">amet.</span>

Can we have this result?

<span class="Lorem">Lorem</span> <span class="ipsum">ipsum</span> <span class="dolor">dolor</span> <span class="sit">sit</span> <span class="amet">amet.</span>

0.7 Kerning Pairs

Would like to get some kerning pair functionality and some tests regarding that.

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.