Dynamic Textual content Alternative – A Listing Aside

Textual content styling is the boring headache of net design. There are solely a handful of fonts which might be universally out there, and complex graphical results are subsequent to not possible utilizing solely normal CSS and HTML. Sticking with the normal typefaces is wise for physique textual content, however in relation to our headings — quick, attention-grabbing blocks of textual content — it will be good to have some selection within the matter. We’ve change into accustomed to this downside and we deal with it both by taking advantage of the few fonts we’ve got, or by fully changing our heading-text with photographs.

Article Continues Under

Most websites that change textual content with photographs achieve this utilizing hand-made photographs, which isn’t so horrible when there are a set variety of headings, but it surely rapidly turns into unmanageable on a website that’s up to date a number of occasions per day. Nonetheless the alternative is carried out, every picture must be certain to the textual content it’s changing. That binding normally manifests itself as an <img> tag, an embedded model sheet, or a customized id attribute. And over time, by format modifications and redesigns, that binding must be managed by somebody.

We are able to neglect all that nonsense. No extra <img> or <span> tags, no extra id attributes or wasted time in Photoshop, and no extra messy CSS hacks. Utilizing JavaScript and PHP, we will generate accessible image-headings utilizing any font we like. And we don’t have to vary the construction of our HTML or CSS in any respect.

View the demo to see Dynamic Textual content Alternative in motion. Then learn on to search out out how one can add the identical performance to your website.

This small PHP script (out there right here) will ship a dynamic PNG picture to our browser every time it’s requested to. Earlier than we set it to work, although, it must be personalized on your particular objective. The primary seven traces of code within the script serve this objective:

  $font_file="font.ttf" ;
  $font_size = 56 ; 
  $text_color="#ffffff" ;
  $background_color="#000000" ;
  $clear = true ;
  $cache_images = true ;
  $cache_folder="cache" ;
  • The $font_file variable should be set to the native path (not the URL) of a True Sort (TTF) or Open Sort (OTF) font in your net server. That is the font that your photographs will probably be created with; you’ll have to add it to the online server from your individual pc.
  • $font_size, unsurprisingly, refers back to the dimension of the font in factors.
  • $text_color and $background_color are hexadecimal shade codes that point out the colour of the textual content, and shade of the picture’s background, respectively.
  • When $clear is ready to true, the perimeters of the picture’s textual content will probably be blended with the $background_color to forestall anti-aliasing, and the precise background shade will probably be fully invisible.
  • By setting $cache_images to true, and $cache_folder to the native path of a writable listing in your net server, this script will save every picture that it creates, caching them for later use. This could considerably pace up supply of photographs to your guests, and is especially necessary on shared, or high-traffic servers.

To put in this script, add it to an internet server that’s configured with PHP assist. Particularly, you will have PHP model 4.3 or greater, compiled with assist for the GD graphics library, 1.6 or greater. If none of which means something to you, electronic mail these necessities to your net host and so they’ll inform you in case your server is appropriate.

Though we used PHP to assemble the pictures on this implementation, your web site doesn’t must be actively utilizing PHP to reap the benefits of this system. No matter the way you generate your HTML pages, whether or not they’re edited by hand or by a CMS, you need to use this system so long as you’ll be able to insert a <script> tag into the <head> of your paperwork. I’ll clarify that element additional, under.

Please be aware that what will be finished with PHP can typically be finished with different instruments as nicely. Perl, ASP, Java servlets, and different server-side programming languages would even be good candidates for producing customized photographs. PHP is a superb selection due to its huge availability, platform independence, and straightforward studying curve. Think about the alternate options for those who require one thing that PHP doesn’t present or for those who select to create your individual image-generation code from scratch. It could be easier, nonetheless, to only adapt the PHP code offered right here.

One factor that our customization of the script didn’t embrace was the textual content that it ought to use to generate our customized photographs. That’s as a result of the textual content that we’re utilizing to provide these photographs will probably be handed to the script through its URL. For instance, loading the URL heading.php?textual content=URLs Are Enjoyable will produce a graphic that reads “URLs Are Enjoyable.” And they’re. However we’ll by no means want to put in writing them ourselves, as a result of JavaScript will do it for us.

Obtain the JavaScript supply file right here.

This method borrows closely from Peter-Paul Koch’s JavaScript Picture Alternative (JIR) methodology. The premise of JIR could be very easy: Many CSS coders exploit browser bugs to cover CSS types from these browsers. These hacks are akin to restricted conditional statements of their code, turning CSS right into a crude programming language. Slightly than utilizing this language-of-bugs to compensate for browser variations, Koch and others have put forth the concept JavaScript — an precise scripting language — might extra intelligently and accessibly carry out the identical process. That is fantastic for our functions as a result of JavaScript additionally provides us extra flexibility. Particularly, we’ll be utilizing it to exchange textual content with photographs that don’t even exist but.

When the web page first hundreds, the script will try to load a small (1×1 pixel) take a look at picture. If this take a look at is profitable, we will conclude that the customer’s browser helps the show of photographs, in any other case it will not have wasted bandwidth downloading it. That is the crux of JIR: By testing for picture assist, we will instantly decide whether or not or not our guests have any use for stylized headings. If they don’t, the script will cease proper there.

Assuming the customer’s browser helps photographs, the script then waits till the web page is fully completed loading, as a result of it could’t change textual content that hasn’t been downloaded but. As soon as the HTML is completed loading, our script will search it for specified components (<h2>, <span>, and so on.) and change the textual content within them with an <img> tag. This dynamic <img> tag has its alt attribute set to the unique textual content, and its src attribute set to the URL of the PHP script that we simply put in. The PHP script then sends again a customized PNG picture, and voila: customized headings.

Weighing in at a hefty eight kilobytes, there’s lots of stuff happening on this nook of the ring, however there are solely two traces that must be personalized earlier than the script will work.

  replaceSelector("h2","heading.php",true);
  var testURL = "take a look at.png";

The replaceSelector operate accepts three parameters: The primary is the CSS-style selector that signifies which components needs to be changed. This selector could also be nearly any legitimate CSS selector, together with id, class, aspect and attribute selectors.

The second parameter is the URL of our customized PHP script.

The third parameter is a real/false worth that signifies whether or not word-wrap needs to be turned on for this alternative. When this flag is ready to true, headings are damaged into a number of photographs, one for every phrase. When it’s false, solely a single, non-breaking picture is generated for every heading.

replaceSelector needs to be known as as soon as for every group of components you need changed by a customized picture. The URLs in these traces will be absolute (http://…) or relative to our HTML file (path/filename).

The testURL variable must be set to the URL of a small (1×1 pixel) take a look at picture.

As soon as these traces are set accurately, you’ll be able to add the JavaScript file to your net server, and apply it to your net pages by including the next line to their <head> tags.

  <script
    kind="textual content/JavaScript"
    src="https://alistapart.com/article/dynatext/alternative.js">
  </script>

Ensure the src attribute in that line factors to the situation that you simply uploaded the JavaScript file to.

That’s all that’s required to get dynamic textual content alternative working; we will cease proper there if we wish to. However there are a couple of elective enhancements we might wish to make earlier than calling it quits.

As beforehand seen right here in ALA, many websites at the moment are using specialised printer model sheets to offer their guests higher arduous copies of their content material. In lots of circumstances this includes reversing the method of picture alternative in order that the printed copy of a web page makes use of precise fonts moderately than graphics, which regularly look poor on high-resolution printers. Sadly, JavaScript falls wanting fixing this downside. As soon as we’ve changed our textual content with a picture, it’s not possible to reverse that course of particularly for printing functions, so we have to discover one other resolution.

As an alternative of attempting to reverse our alternative course of, we will do some planning forward. Together with inserting an <img> tag into our headings, we will additionally insert a <span> tag that comprises the unique heading textual content. And we will set that span’s show property to none, in order that it doesn’t present up onscreen. Now we’ve got two copies of our unique textual content: One in a visual picture, and one in an un-displayed span. By giving every of those components identifiable class attributes (“alternative”, and “print-text,” respectively), and by including in a print-specific model sheet, we will swap their show properties after they’re printed.

The next model sheet (obtain a pattern CSS file right here) might be used to generate an applicable print model of your web page:

  span.print-text {
    show: inline !necessary;
  }
  img.alternative {
    show: none;
  }

As soon as we’ve uploaded this model sheet -to our net server, we solely want to vary two traces in our JavaScript to make it work:

  var doNotPrintImages = false;
  var printerCSS = "replacement-print.css";

By setting doNotPrintImages to true, and printerCSS to the URL of the print model sheet we simply created, the script will robotically insert the suitable CSS <hyperlink> into our doc’s <head> tag.

Flicker Free#section5

As a result of our script can’t start changing components till after the complete doc has loaded, there’ll typically be a fast flash of unstyled content material because the browser waits for the alternative course of to start. That is much less of an issue than it’s a minor annoyance, however because it’s avoidable we would as nicely repair it. With the assistance of one other small model sheet, we will do exactly that.

Earlier than the doc’s physique begins loading we will dynamically insert a mode sheet that can disguise these components fully. Since linked CSS recordsdata are utilized even because the doc is rendering, no content material will probably be seen throughout this era. As soon as our alternative method is completed executing we will disable this model sheet and our newly stylized headings will probably be seen as soon as extra.

For instance, in case your web page was set as much as change <h2> tags, the next model sheet (out there right here) would disguise them till our alternative method was completed:

  h2 {
    visibility: hidden;
  }

There’s a slight downside with this method, nonetheless. Our total method is dependent upon the loading of a take a look at image to point whether or not the browser helps photographs. If the picture by no means hundreds, our method won’t ever activate. And if our method by no means prompts, the model sheet that hides our unstyled headings won’t ever be deactivated. Due to this, guests who’ve disabled picture assist of their browsers, however who’re nonetheless able to utilizing JavaScript and CSS, will see nothing however empty house the place our headings ought to have been.

We’ll do our half to enhance this poor minority’s already-difficult looking expertise by including a brief timeout worth to the script. If the take a look at picture hasn’t been efficiently loaded after one or two seconds (or nonetheless lengthy you see match), the script will robotically disable this model sheet, and the headings will reappear. These one or two seconds are a slight inconvenience for this exceptionally uncommon particular person, but it surely solves the glint downside for the opposite 99.99% of our guests. What’s necessary is that we keep accessibility for everybody.

To allow this elective customization, and to take away the temporary flash of unstyled content material, you need to edit three traces within the JavaScript supply:

  var hideFlicker = false;
  var hideFlickerCSS = "replacement-screen.css";
  var hideFlickerTimeout = 1000;

Set hideFlicker = true, and hideFlickerCSS to the URL of the CSS file that you simply simply created to cover your headers.

hideFlickerTimeout needs to be set to the utmost variety of milliseconds (i.e. 1/1000 seconds) that the script will let go earlier than disabling that model sheet.

Notes and Options#section6

Older variations of Mozilla, together with Netscape 6.2, contained a bug the place the browser would obtain photographs even when the person had instructed it to not show them. This clearly made no sense, and has been fastened since model 1.4. Though this system will usually work with none issues in these browsers, it’ll incorrectly diagnose picture assist and fail when guests utilizing these browsers have photographs disabled. I don’t take into account this overwhelmingly uncommon prevalence to be a severe disadvantage, but it surely’s value noting for completeness. There may be at the moment no workaround for this downside.

Use this system with a translator service, like Google or Altavista’s Babelfish. So long as your font helps the overseas character set, the dynamic photographs will probably be translated as nicely.

The textual content that you simply change doesn’t need to be within a heading tag (<h1>, <h2>, and so on.); it may be any aspect on the web page. With some pretty easy changes, and a few manipulation of float values, this system might produce dynamic drop-caps for any paragraph you apply it to.

You too can change <a> tags, giving your web page stylized hyperlinks, though getting rollovers to work would require extra customization.

As an alternative of changing content material with dynamically generated <img> tags, this system might keep away from utilizing PHP altogether and as an alternative insert dynamic Flash animations.

Acknowledgements#section7

Peter-Paul Koch, for his JavaScript Picture Alternative method.

Simon Willison, for this getElementsBySelector operate.

Stuart Langridge, for unobtrusive JavaScript methods.

Leave a Comment