Category: JQuery

CSS or Javascript? Internal Link Targets and Fixed Headers

How do you keep target links from getting hidden under fixed headers?

Do you want to use CSS or Javascript when navigating to internal page targets on pages with fixed headers? It can be tricky getting an internal page target to position itself properly at the top of the visible area in a browser window when there are fixed header elements at the top of the page. Here are some thoughts about how to approach and resolve the issues that can come up.

Using Internal Page Targets

A convenient way to navigate within the content of a long HTML document is to use the id attributes of elements on the page as link targets. By appending a # sign and the id of one of these elements to the URL in the href of a link (eg: <a href="page.html#target">Page Target</a> for an element with an id of "target" on page.html) you can make the browser scroll directly to that position on the page when the page is loaded.

The body for a page might look like this:

<nav class="fixed-element">
	<ul>
		<li><a href="#some_element">Element One</a></li>
		<li><a href="#some_other_element">Element Two</a></li>
		<li><a href="#a_third_element">Element Three</a></li>
	</ul>
</nav>
<section class="content">
	<h1>This is a long page</h1>
	<h2 id="some_element">Some Element</h2>
	<p>This is a paragraph of text associated with some element.</p>
	<p>(Imagine it's a long one that would force lower content to scroll off the screen.)</p>
	<h2 id="some_other_element">Some Other Element</h2>
	<p>This is a paragraph of text associated with some other element.</p>
	<p>(Imagine it's also a long one.)</p>
	<h2 id="a_third_element">A Third Element</h2>
	<p>This is a paragraph of text associated with a third element.</p>
	<p>(Imagine it's also a long one. You get the idea.)</p>
</section>

The CSS for this page might look like this

.fixed-element {
	width: 100%;
	height: 80px;
	position: fixed;
	top: 0;
	background: #900;
}
.fixed-element ul {
	overflow: auto;
}
.fixed-element li {
	list-style-type: none;
	margin-right: 10px;
	float: left;
}
.fixed-element a {
	display: block;
	color: #fff;
}
.content {
	padding-top: 80px;
}

In this case your page has a toolbar at the top, or some other fixed header. These are usually positioned with fixed or absolute positioning at the top of the page, so the rest of the page scrolls underneath. The page navigation is using just a target id for an element on the page in the href of the links to refresh the scroll position.

When you link directly to an internal target, the page will scroll the target element all the way to the top of the window, without regard to the positioning of the header, and the content you are trying to target will be hidden under your fixed header. The problem is getting the browser to scroll to a position that allows your target content to be viewed directly below the fixed header.

A Javascript approach

One way to approach this is with Javascript. There are native Javascript ways to get the offset of the target elements from the top of the window, and to set the scroll position. However, to deal with cross-browser issues, it is generally more practical to use a popular library such as JQuery.

To do this dynamically, you need to determine on page load if the URL has a target identifier appended. When there is one, it is available in Javascript's location object, in the hash property. By testing to see if location.hash exists, and then using it to create a JQuery object, you can get its offset().top value. This value, minus the height of the fixed element, can be used to adjust the scrollTop() of the JQuery object for the body element.

The Javascript to make this work might look like this

$(function() {
	if (location.hash) {
		var target_position = $(location.hash).offset().top;
		$('body').scrollTop(target_position - 80);
	}
});

This will work because JQuery's ready function will be called every time the page is refreshed. When a target link is clicked, the effect is the same as refreshing the page, which again invokes the JQuery.

A CSS approach

An alternative is to add a class to the page targets, and using some CSS to trick the browser into believing that the top of the page is actually offset from the top of the target element by the appropriate distance.

The additional CSS for this page might look like this

.link-target {
	padding-top: 80px;
	margin-top: -80px;
}

The revised content section might look like this:

<section class="content">
	<h1>This is a long page</h1>
	<h2 id="some_element" class="link-target">Some Element</h2>
	<p>This is a paragraph of text associated with some element.</p>
	<p>(Imagine it's a long one.)</p>
	<h2 id="some_other_element" class="link-target">Some Other Element</h2>
	<p>This is a paragraph of text associated with some other element</p>
	<p>(Imagine it's also a long one.)</p>
</section>

By adding extra padding to the top of the element you want to have appear at the top of the page, you can trick the browser into scrolling to a position that is high enough on the page to display your content below the fixed elements at the top. Using a negative top margin will prevent this extra padding from changing the existing layout of the elements on the page, so you don't create additional white space above the target elements. Of course, you may need to adjust the values for the padding and negative margin depending on the styles you already have.

It's your choice how you would prefer to manage the issue. The Javascript approach doesn't require any addition markup in your pages, but it won't work if Javascript is disabled. The CSS approach requires each target to have a class, and may involve a little adjustment to accommodate your existing layout, but it doesn't require running scripts to achieve the desired visual effect.

HTML 5, Progressive Enhancement, and Semantic HTML

HTML 5 is supposed to change everything all over again, but can we use progressive enhancement, or does HTML 5 mean starting from scratch after all the lessons we've learned about semantic HTML and beautiful markup from HTML 4?

Different web browsers interpret HTML differently. It's a fact of life, and it can feel like a curse to HTML developers when their clean semantic HTML and CSS code fail to deliver the same results to users across all browsers. Yet the folks developing the next generation of browsers continue to push forward with browsers that include incompatible features from unreleased standards, or proprietary standards that lure us into innocently building web apps that break for our poor users on competing browsers. That's happening right now with CSS 3 and HTML 5 (branded as "HTML5" by some and just plain "HTML" by others).

The proposed HTML 5 standards introduce a number of useful semantic elements that can help HTML developers plan the structure of their documents. But even with the new web standards in flux, the savvy HTML developer comfortable with the concept of progressive enhancement can start using these elements right now.

New HTML 5 Semantic Elements

Among the new semantic HTML elements to help a developer structure a web page are new general container elements called header, footer, and nav. These are block-level elements that can replace the conventional div with a class of header, footer, or nav commonly used by HTML developers for branding, nav bar, and attribution.

We now have article, section, and aside elements to group content within a page. And since a single page of HTML 5 may have multiple sections with multiple articles, or multiple articles with multiple sections, the cascading style sheet selectors for these elements should provide inheritable styles, just as it would be with a set of divs that share the same class.

Each of these articles or sections, as well as the main content area, may now also have its own hierarchy of headers from h1 to h6, wrapped safely inside its own header elements. No more limiting yourself to a single h1 per page. The CSS styles for these headers can be inherited logically based on the containers.

Progressive Enhancement

But we still live in a world where we have no control over the browsers a user might have. Is it an old one, designed well before standards for HTML 5 were even proposed? Or is it a new one, with a unique idea of how to interpret the elements in this new unfinished web standard?

Happily, there are some Javascript utilities that are coming to the rescue. One of the smallest and simplest is the Google HTML 5 Shim. This simply allows older browsers to recognize the current set of HTML 5 elements for the sake of CSS styling. Yes, this even works in Internet Explorer 6!

Another tool is Modernizr. This handy bit of code includes a shim, but also adds several enhancements that allow features such as advanced CSS3 selectors to take advantage of the native features of older browsers. After all, if we're going to create our beautiful markup, we want our cascading style sheets to have all the modern advantages, too. To get started using it, all you have to do is include the script, and add a "no-js" class to your html element.

What We're Losing

The proposed XHTML standard many of us adopted—in spite of the way it was actually interpreted by web browsers—isn't going away. However, future development has been halted, and we are being encouraged to use HTML 5 instead for web development. HTML 5, like earlier flavors of HTML, doesn't require us to close all of our elements the way XHTML does, and supports target tags for opening links in separate windows. Of course, creating structured HTML with XML-inspired closed elements is still a good practice, as it makes our page structure cleaner and easier to manage and maintain.

One of the convenient enhancements that follows the practice of actual HTML developers who ignored the published standard is that we no longer have to worry about including block-level elements inside our anchor elements. It is now permitted to put an entire div inside a link, and our HTML 5 markup with still be compliant.

And although we've all learned to favor em and strong elements over i and b elements...some of the time...HTML 5 has reinvented our old bold and italic friends, redefining them based on how they have been used by HTML developers over the years instead of deprecating them.

There are plenty of other changes in the proposed HTML 5 standards, but these are a few that might get you started down the right path as you apply the concepts of progressive enhancement to your HTML development.

So with a good sense of semantic structure, we can approach any web design we encounter and parse it into clean, cross-browser compliant HTML 5 based on the web standards that exist. It just takes a little sense, a little discipline, and some Javascript tricks, to help our web sites survive whatever the browser developers throw at us!

Truncating Styled Text to Fit a Container Using JQuery

Recently I had the need to truncate a section of styled HTML text so it would fit inside a container with a specific pixel width. You might have thought this would be something pretty easy to make happen with a little JQuery and some .css() and .width() commands.

You would have been mistaken. I know I was.

Among the tricky aspects was my desire that the text retain its styling, regardless of the width of the container. I also wanted it to truncate at the appropriate complete letter, rather than chop a word off in the middle of a letter. I wanted to be able to specify a string to use to indicate truncation (eg: "..."). I wanted the complete text to be preserved, and added to the element as a title tag so that it would be available to readers who hovered over the truncated text. And of course, I wanted it to work seamlessly across browsers.

What I decided I needed was a temporary DOM object where I could copy the styled text. I needed something that would report its width based on the width of the text it contained. That ruled out both block elements such as divs (which take their width from their container) and inline elements such as spans (which report zero when queried about their width, regardless of their actual contents). What to do?

Then I realized that tables adjust their width to the width of their contents, AND are able to report that width when queried. Eureka! I just needed to add a temporary table to the DOM somewhere that it would be untouched by other styling, and make sure all the elements that made up the table had no padding, margin, or border settings. I didn't need to worry about the semantics of using a table this way since I was going to remove it from the DOM as soon as I was done with it. You won't hear me saying things like that very often, but in this case even I was satisfied.

To copy the styled text, I had to take a two-step approach. After creating a temporary table, I copied the contents of the original element I wanted to measure, and then copied each of the original element's font-relates styles and applied them to the inner td of the table. Firefox immediately rewarded me with an accurate measurement, which I could use in a recursive loop to chop away one letter at a time until I had the width I desired. It looked like I was going to be done with this one quickly.

I replaced the contents of the original element with the truncated text easily. I tossed in a call to cache the full text and apply it as a title attribute if the text needed truncating. I even made a quick swap of the truncation indicator text ("...") into the styled table cell from the start, so I could account for the pixels that added to the width. It was looking pretty sweet.

Until I tested it in Internet Explorer.

Now the creepy thing was that it even worked in Internet Explorer with the font size set to the default value. But as soon as I tried font sizes that were larger or smaller, I started seeing the width vary in odd ways. Larger fonts would result in a reported width that was wider by an ever-increasing factor, resulting in truncated strings that were too short for the space. Smaller fonts did the opposite, reporting a narrower width than they actually required, resulting in truncated strings too long to fit the desired width. It wasn't a straight line rate of change; I could see there was some mysterious equation at work here.

I will admit it took me a few hours of fiddling, and I had to dust off that part of my brain that was paying attention during high school algebra. What I discovered (and this is the golden nugget in this chicken soup of a blog posting) was that Microsoft calculates the pixel size of rendered text based on the square root of the desired font size divided by a base font size of 16.

That works out like this in Internet Explorer:

Math.sqrt(parseFloat($('#element').css("font-size"))/16)

Whereas other browsers use a formula more like this:

parseFloat($('#element').css("font-size"))/16

Once I had that worked out, the rest of the project came together nicely. Here's the code for the set of JQuery plugins I ended up with. One does the truncation, and relies on the other one to get the width of the text:

(function ($) {
  // A plugin to truncate the text inside an element to a given width
  // This plugin depends on the textWidth() plugin, which should be below
  $.fn.textTruncate = function(width,marginText) {
    var that = this;
    var width = width || "250"; // default width of 250 px
    var marginText = marginText || "..."; // default margin text of "..."
    that.css("visibility","hidden"); // The element should be hidden in CSS
    return this.each(function () {
      // A table as a temporary dom element for measuring the text width
      $('body').append('<table id="textWidthMeasurer" style="padding:0;margin:0;border:0;width:auto;zoom:1;position:relative;"><tr style="padding:0;margin:0;border:0;"><td style="padding:0;margin:0;border:0;white-space:nowrap;">' + marginText + '</td></tr></table>');
      var measurer = $('#textWidthMeasurer');
      var margin = measurer.textWidth(measurer); 
      if (that.textWidth(measurer) > width) {
        var contentLength = that.text().length;
        that.attr("title",that.text());
        while (that.textWidth(measurer) >= width - margin) {
          contentLength--;
          that.text(that.text().substring(0,contentLength));
        }
        that.text($.trim(that.text()) + marginText);
      }      
      // Make the element visible and remove the measuring table
      that.css("visibility","visible");
      $('#textWidthMeasurer').remove();
    });
  };
  
  // A helper plugin to get the width of the text inside an element
  $.fn.textWidth = function(context,css) {
    var that = this;
    var context = context || null;
    var css = css || null;
    // Optionally pass in an array of additional CSS properties to use for measuring
    var properties = ['font-family','font-weight','font-style','letter-spacing'];
    if ((css != null) &amp;&amp; (css[0] != null)) {
      properties.concat(css);
    } 
    // Establish a default context if none is passed in (slow)
    if (context == null) {
      if ($('#textWidthMeasurer') == null) {
        $('body').append('<table id="textWidthMeasurer" style="padding:0;margin:0;border:0;width:auto;zoom:1;position:relative;"><tr style="padding:0;margin:0;border:0;"><td style="padding:0;margin:0;border:0;white-space:nowrap;"></td></tr></table>');
      }
      var context = $('#textWidthMeasurer');
    }
    var target = $('td',context);
    // IE uses a bizarre formula to calculate the pixel value of font sizes:
    var fontSize = ($.browser.msie) ?
      Math.sqrt(parseFloat(that.css("font-size"))/16) + "em" :
      parseFloat(that.css("font-size"))/16 + "em";
    target.text(that.text()).css('font-size',fontSize);
    properties.forEach(function(property) { 
      target.css(property,that.css(property));
    });
    var width = context.width();
    return width;
  };
})(jQuery);

If you want a demo, you can check out a sample page with styled text that adjusts to match the width specified.

You can also download the source code for the plugin set. It's open source, and free to use in commercial or personal projects under an MIT (X11) license.

Let me know what you think.

How to Coordinate CSS with Javascript

Javascript is used to change the content of an HTML page, and apply various CSS styles, dynamically in response to user action and other factors. When writing HTML and CSS, consider how you might use Javascript to manipulate the pages. It is important to provide the Javascript programmers with useful semantic targets which they can populate with new information, or style by applying different CSS. For example, if there is a word in your document that you know will be generated in Javacscript, create a <span>...</span> to contain it, and allow the Javascript programmer to assign it an appropriate id.

If the Javascript programmer needs to alter the HTML, move HTML blocks from one place to another using Javascript commands such as the JQuery commands .after() or .before(), or dynamically generate CSS styles not defined in our CSS pages, our application will be more brittle and harder to manipulate in the future.

Knowing how the page will work before coding the HTML skeleton is critical. For example, it allows us to create the spans which the Javascript programmers will fill with information, and the divs which will be shown, hidden, and otherwise manipulated. With AJAX, a single page may change radically over its lifetime on a user's screen. Examine the page carefully to see which elements will change, and which ones will stay the same. We are less likely to break the layout of a page if we replace the content of a single defined header div across the lifetime of the page than we are if we hide that header div and then show another in the same location.

The JQuery Javascript library allows programmers to target HTML elements in a page using the same CSS definitions that define the style of the elements. While that is convenient, it is generally more flexible to separate the functionality of the Javascript from the presentation of the CSS. That way, if things change in the style, they are less likely to compromise the program logic. Javascript is also much more efficient about parsing a large document for id's than for classes. Therefore, I recommend using unique id's for targeting Javascript to an element, and using classes and inheritance to apply styles to an element.

Efficient HTML Skeleton Construction

The basics are always worth considering again. Sometimes it's the obvious things you don't think about that can cause the worst problems. The wrong doctype can spoil all your hard cross-browser CSS styling efforts. The wrong class name can lock you into awkward naming conventions. Even something as common as putting your script tags in the head of your document can slow down your site.

As we enter 2009, this is my state-of-the-art approach to constructing an efficient, semantic, and flexible web site. I'll start with the HTML skeleton:

A basic HTML page skeleton should tell the browser what kind of content to present, in what order the content should appear, and what to do with it.

I start with a !DOCTYPE to tell the browser what our page will consist of; for example, a public HTML document that complies with w3C standards for HTML 4.01 Strict.

Next I have the HTML element, which consists of a HEAD and a BODY element. Note that you have to close the HTML, HEAD, and BODY tags (/HTML, /HEAD, /BODY)at the end of each definition.

In the HEAD I include the title, the encoding standard, and references to external stylesheet CSS files, starting with a CSS reset script, a possible CSS script with code for all the shared elements across a set of pages, and then a CSS script with code specific to this particular page.

In the BODY I create elements of semantic HTML and fill them with content.

At the end of the BODY tag I include SCRIPT tags. These tags load external JavaScript libraries, such as JQuery, or contain document-specific Javascript.

The code below will create a page that looks like this.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
    <title>Hello Page</title> 
	<meta http-equiv="Content-Type" content="text/html;charset=ansi" >
    <link rel="stylesheet" href="css/reset.css" type="text/css">
    <link rel="stylesheet" href="css/hello.css" type="text/css">
</head> 
<body> 
    <p class="description">The box on this page is ten lines down and has a dotted border.</p> 
    <div id="mainContent"> 
        <p>Hello World!</p> 
    </div> 
	<script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>  
	<script type="text/javascript"> 
	    $(function() { 
	        $("#mainContent").click( function() { 
	            alert("You clicked me"); 
	        }); 
	    }); 
	</script> 
</body> 
</html>

Since this page is called hello.html, the visual style of the elements on this page is defined in the a hello.css file, which is coded like this:

/* Formatting for the hello.html page */  
mainContent {width:50%;position:relative;top:10em;margin:0.5em;padding:0.5em;border:2px dotted #ff0;}  
  
/* Styles for the hello.html page */  
body {color:#fff;background-color:#005;}  
mainContent p {color:#fcc;text-align:center;font-family:impact,helvetica,sans-serif;font-size:3em;} 
.description {text-align:center;font-style:italic;}