Search Results

Keyword: ‘anchor tag’

Using JavaScript to Style Active Navigation Elements

active navigation element

I’m all about efficiency when I’m writing web code. Any time I find myself writing the same functionality more than once or twice, I try to consider whether my repeated code could be wrapped into a function of some sort.

Navigation is often one of those areas where I try to improve my efficiency. I like my navigation elements to pull double duty. I want them to:

  1. Show the user where they can go, and
  2. Show the user where they currently are.

In other words, I want some sort of visual indication in my navigation that shows my user which section of my site they’re in. You can see this on the CSS Newbie site: if you click on the TOC (Table of Contents) link in the bar at the top of the page, you’ll see that link gets special styling when the table of content loads.

Now, I could manually set this on every page using a CSS class. But that’s inefficient — depending on the size of my site, I could end up writing dozens or hundreds of lines of one-off code. And why go to all that work, when you could just wrap it all up into a nice JavaScript function?

First, I’ll explain the logic behind my functions — because they won’t work equally well for every site. Then I’ll walk you through a few examples of the code that makes it all happen.

The Logic

All of my functions assume a very clean, straightforward directory structure. For example, if you have an About section, a Blog section, and a Contact section on your site, a logical directory structure might be:

/
/about/
/blog/
/contact/

And if you had several blog entries inside your blog directory, your structure might grow like this:

/
/about/
/blog/
/blog/post-one/
/blog/post-two/
/blog/post-three/
/contact/

And therefore, a function could logically assume that anything inside the blog directory should be considered a part of the blog section of your site, and mark the blog link as active for those pages. This makes our job a lot easier. And luckily, most CMS platforms make this sort of directory structure pretty easy to create.

The functions also assume that you have either a fairly shallow directory structure, or that you’re not linking to too many similarly nested directories. What I mean by this is, if you have this sort of a structure:

/
/contact/
/contact/me/
/contact/me/here/

And you wanted to link to both /contact/ and /contact/me/here/ in your navigation bar, you might run into problems distinguishing between the two. There are ways to increase precision, but they come at the cost of flexibility.

But enough of that. Let’s get to the good stuff!

A JavaScript Solution

I’ve written about this method before, when I previously talked about building intelligent navigation bars. This technique is nice because it doesn’t rely on any JS frameworks, so you can add it to older sites without needing jQuery or the like. The basic function looks like this:

function setActive() {
  aObj = document.getElementById('nav').getElementsByTagName('a');
  for(i=0;i<aObj.length;i++) {
    if(document.location.href.indexOf(aObj[i].href)>=0) {
      aObj[i].className='active';
    }
  }
}

This function looks for an element with an id of “nav” (presumably your navigation bar), then looks at each of the anchor tags inside it. It then compares the anchor tag’s href tag with the page’s URL. If the href tag is contained within the URL anywhere, it gives that link a class of “active,” which I can then style specially in my CSS.

As an example of what I mean by all that, if I had an anchor tag in my navigation bar that linked to “/blog/” and the page I was on was “/blog/this-is-a-post.html”, my blog link would be styled as active, because “/blog/” is contained within “/blog/this-is-a-post.html”.

As a final note, you wouldn’t want to call this function until the page was finished loading: if you call it too soon, your links won’t exist yet! So you can either call it at the very end of your document, or dynamically call it when your page is done loading, with something like this:

window.onload = setActive;

A jQuery Solution

If you are already loading a framework like jQuery (like I do on almost every site I work on these days), this sort of functionality could be written even more succinctly. And like I said earlier, I’m a sucker for efficiency. Here’s a jQuery solution that does essentially the same thing in a much smaller space:

$(document).ready(function() {
	$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

This function is making use of both native JavaScript and jQuery tricks to reach a whole new level of brevity. First, the whole thing is wrapped in a “document ready” function, which means it won’t fire until the page is loaded and our links are in place. Next, we’re looking for anchor tags inside our “nav” ID. And really, we’re looking for a very specific anchor tag: one whose href starts with (^=) a slash, followed by a part of our page’s location (location.pathname). Specifically, we’re looking for the first directory in our page’s URL.

We’re doing this by making use of the JavaScript split() method, which lets us take any string (for example, “/blog/this-is-a-post.html”) and break it into an array based on a substring (in our case, the forward slash). If you’re familiar with PHP, it’s similar to the explode() function. In our example, we’d end up with a three-part array that looked like this:

["","blog","this-is-a-post.html"]

Which means that if we look at the second value of our array (arrays start counting at zero, so [1] is the second value), that should give our first-level directory (”blog”, in our example). This lets us match any subsequent child directories with our parent in the navigation bar.

Tweaking for Home Links

Our jQuery function works great in most scenarios, but it fails if you have a “home” link where you’re just pointing to the root directory, like this:

<a href="/">Home</a>

And because I tend to have a link like that, I needed a workaround. Here’s a way to get around that with just a little more code to account for our special case:

$(document).ready(function() {
	if(location.pathname != "/") {
		$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
	} else $('#nav a:eq(0)').addClass('active');
});

Here, we’re checking to see if we’re in the root directory. If so, we’re skipping the loop through our anchor tags and just making a specific anchor tag active. In this case, I’m giving the active class to the first anchor in our list (which is the most common location for a home link).

And that’s that. If you know of even more efficient or fool-proof ways to accomplish this task, I’d love to hear about them in the comments section. Or if you’re skilled in a framework other than jQuery, feel free to share the equivalent code!

Note: I apologize for the long gap between articles. I had some problems while rebuilding my PC (DOA motherboard) and was without my computer for several weeks.

Read More

CSS Blog

A Simple jQuery Stylesheet Switcher

jQuery stylesheeet switcher

There are lots of reasons you might want to offer your users more than one CSS file for your website:

  • You want to offer a “stylish” low-contrast and an easy-to-read high-contrast version of your site.
  • You have many low-vision readers and want to give them easy access to a customized stylesheet with a larger typeface.
  • Your site is schizophrenic and you want to be able to change the look quickly.

Whatever the reason, it’s amazingly easy to create a function that swaps between multiple stylesheets using jQuery.

The first step of course is to build several different CSS files, which we’ll then swap between. Once that is done, we can dive into the XHTML and jQuery that makes the magic happen.

The XHTML

First, we need to create a set of links that will allow the user to swap between CSS files. You can make this as simple or as fancy as you’d like. For the sake of brevity, my links are simple:

<ul id="nav">
	<li><a href="#" rel="/path/to/style1.css">Default CSS</a></li>
	<li><a href="#" rel="/path/to/style2.css">Larger Text</a></li>
	<li><a href="#" rel="/path/to/style3.css">Something Different</a></li>
</ul>

Here I have three links, each with a “rel” attribute indicating which CSS file the link will load. Technically, I could have just as easily put this information in the “href” attribute, but I didn’t want to for one specific reason: if the user has JavaScript disabled and the CSS file is listed in the href, then clicking the link will send the user to the CSS file directly (not loading it like we intended). But our way, if JS is disabled, the user gets nothing at all: which is certainly preferable to the less savory alternative.

The jQuery

Like I promised, the jQuery is really simple:

$(document).ready(function() {
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		return false;
	});
});

This function waits until the document is loaded (generally an important step when interacting with the DOM), then attaches a click function to each of our nav anchors. The function basically says, “when someone clicks on this link, replace the link (stylesheet) tag’s href attribute with the contents of this link’s rel attribute.” The “return false” at the end just stops the browser from trying to follow the link.

Of course, you might have to get more detailed if you have more than one link tag, for example, but that’s easily done by giving the link tag a class (”changeme,” for argument’s sake), and writing something like this:

$("link.changeme").attr("href",$(this).attr('rel'));

And while this stylesheet switcher is already complete, we might want to give it some memory: after all, your users might get annoyed if they have to switch their styles back to their preferences every time they visit your site. For that, we’ll need to set a cookie. And to make that easier, I’ll use the jQuery cookie plugin (which I’ve talked about previously when building a popout ad).

With the plugin loaded, we can modify our jQuery thusly:

$(document).ready(function() {
	if($.cookie("css")) {
		$("link").attr("href",$.cookie("css"));
	}
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
		return false;
	});
});

Now we have two statements. The first one checks as soon as the page is done loading to see if a cookie called “css” has been set. If so, it sets the stylesheet to be the one indicated in that cookie. Otherwise, it does nothing.

Our click function is much the same, except after we set the stylesheet, we also set a cookie. This cookie doesn’t expire for an entire year (and each time the user changes their stylesheet preferences, it would reset this timer), giving them a good 365 of CSS bliss.

Fine Tuning

There is one minor annoyance with this stylesheet switcher: there’s generally a flash of the “default” CSS when the user loads the page. That’s because the script waits until the document is “ready” before switching the link’s href. There is a way around this: moving the first “if” statement outside of the document ready function, like so:

if($.cookie("css")) {
	$("link").attr("href",$.cookie("css"));
}
$(document).ready(function() {
	$("#nav li a").click(function() {
		$("link").attr("href",$(this).attr('rel'));
		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
		return false;
	});
});

Generally speaking, you don’t want to run any jQuery until your document is ready. However, so long as your jQuery comes after your link tag in your document structure, like shown below, this shouldn’t be a major concern:

<link rel="stylesheet" type="text/css" href="style1.css" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript" language="javascript" src="jquery.cookie.js"></script>
<script>... your jQuery goes here...</script>

This means your jQuery will run before the document is done loading, and thus your link tag’s href will be swapped before your CSS has been applied. As I said before, it’s generally a bad idea to manipulate the DOM before document ready, but because we know the exact tag we want to manipulate and can place our jQuery below it in the DOM, we should be safe in this one specific instance.

Here’s an example if you would like to see this technique in action.

Read More

CSS Blog

12 Creative and Cool Uses for the CSS Border Property

random art using the CSS border property

If CSS properties attended high school, you would never expect to see the border property sitting at the cool kids’ table. Sure, it’s a useful property and all — as long as you’re looking accentuate the boxiness of a design, right?

Actually, you’d be surprised at just how cool the border property can be. Please take the following dozen exhibits as proof that the CSS border property is a lot cooler than we give it credit for.

Jazzing Up Anchors

I’ve written here before about jazzing up anchor tags by changing the color, removing the underline, and adding background images. But border can be a great way to add a bit of visual style to your anchors without adding that great bit of accessibility that the underline provides. For example, CSS Newbie’s article links are currently styled with a dotted border, like so:

.entry a {
	color: #253c93;
	text-decoration: none;
	border-bottom: 1px dotted #253c93; }
.entry a:hover {
	border-bottom: 1px solid #253c93; }

That gives me a nice dotted border that turns solid when the user hovers over the link. All sorts of style and accessibility without that so-’90s underline.

Build a Postage Stamp

CSS postage stamp

A while back, I ran across a cool little technique for faking a postage stamp using the CSS border property. The original link seems to have been lost from the web, but here’s the basic technique, in XHTML:

<div class="stamp">
	<p>99&cent;</p>
</div>

And CSS:

.stamp {
	width: 500px;
	height: 414px;
	background: #fff url(george.jpg) no-repeat;
	border: 12px dashed #1b1a19; }
.stamp p {
	color: #fff;
	margin: 10px 10px 0 0;
	font: bold 60px Georgia, "Times New Roman", Times, serif;
	text-align: right; }

Now, you could obviously take this even further with a bit of skill and a degree in something other than Rhetoric, but I think you get the idea. You can see the example live here.

Prettier Images

Borders are a great way to make your excellent images stand out even more. I wrote an article on the subject a while back, but here’s the basic idea:

img.photo {
	border: 1px solid #999;
	background-color: #fcfcfc;
	padding: 4px;}

You can see a similar technique used on CSS Newbie’s current design around all of the images in the articles, as well as the ads in the sidebar. As you can see, the technique can be subtle but visually pleasing if used properly.

Homemade Coupons

If you’re ever required to design an online coupon, you needn’t turn straight to Photoshop or the like. You can craft a coupon easily with just a bit of CSS:

.coupon {
	width: 250px;
	padding: 10px;
	text-align: center;
	border: 3px dashed #ccc; }

Just that speck of code gives me a nice coupon that looks something like this:

CSS coupon

You’ll have your readers printing and clipping in no time.

Better Blockquotes

CSS blockquote

Blockquotes are often useful, seldom used. But if you have a website that often refers to the words of others, a well-styled blockquote will go a long way towards impressing your readers with your borrowed prose:

blockquote {
	margin: 1em 3em;
	color: #999;
	border-left: 2px solid #999;
	padding-left: 1em; }

Just a touch of code, and voila… instant credibility!

Hunt Archaic Code

diagnostic CSS

If you ever take over a website (or perhaps built a website) that is still using the Code of Yesteryear, consider turning to CSS and the border property for help hunting down bits of HTML soup that could use a bit less seasoning:

font, center, s, u, b, i {
	color: #000;
	font-weight: bold;
	background-color: #f99;
	border: 3px solid #c00; }

For more information on this useful technique, see my article on finding deprecated elements with diagnostic CSS highlighting. It just might save your life someday. But I doubt it.

Round the Bend

CSS rounded  border

So far, all of our techniques have had one thing in common: boxy edges. But if you’re using a browser developed within the last five or so years (read: not IE6), you’re not limited to those same old dull right angles. This article from last August shows us that CSS3 offers us a way of breaking out of — or at least bending the corners of — the CSS box:

div.rounded {
	background-color: #666;
	color: #fff;
	font-weight: bold;
	padding: 10px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px; }

The border-radius properties allow us to round the corners of elements without having to resort to images. Cool indeed!

Angle it In

Eric Meyer slant

Of course, not all angles are bad angles… if used properly. Way back in the day, CSS guru Eric Meyer pointed out a way to use borders to create some pretty wicked angles. If you’d like to learn more about this technique, his site is a great place to start.

CSS Drawings

And now for a bit of fun! The following excellent (and cool) examples are all drawn using the CSS border property.

CSS lcd clock

This functional LCD-style digital clock was built using CSS borders to create the lines of the LCD. Check out tanfa.co.uk to see it in action!

CSS skyline

There’s something very pop-art about this CSS skyline. It leans heavily on the border property to create the buildings and windows.

random art using the CSS border property

Here’s a random art generator that combines HTML, JavaScript, and the CSS border property to create random examples of modern art. If you hit the “update” button long enough, you’re bound to find something worthy of hanging on your (cubicle?) wall.

CSS house

Christopher Hester is a man with fantastic CSS skill, incalculable patience, and presumably no girlfriend — at least until he started impressing the ladies with this house he built with the CSS border property. And be sure to check out his second CSS house, which he built using background colors and approximately 50 gazillion non-semantic divs.

If you know of any other fantastic uses for the CSS border property, be sure to mention them in the comments!

Read More

CSS Blog

Setting the CSS Class of Items

Setting the CSS Class of Items. Appearance Skins. Tutorial: Creating A Custom Skin … The CSS class of an item is applied to the anchor (<a>) tag that represents the …

Source

CSS Help

anchor code

anchor (1) css (1) Never been to DZone Snippets before? … By specifying a class name before the a: you can restrict anchor css to certain classes. …

Source

CSS Help

Removing underline from anchor tag

removing underline from anchor tag … Home / Forums Index / Browser Side World / CSS. CSS. Removing underline from anchor tag …

Source

CSS Help

css code

By specifying a class name before the a: you can restrict anchor css to certain classes. … to css anchor by jalessi on May 07, 2007. CSS Hacks for opacity …

Source

CSS Help

basic anchor tags in CSS [Archive] - Dynamic Drive Forums

[Archive] basic anchor tags in CSS Dynamic Drive scripts help … however when my CSS has basic anchor tags in it, these overwrite the STYLES for …

Source

CSS Help

CSS text generator - CSS tricks with inline CSS for forum n message board

Code Maker- CSS text tricks for forums or message boards. … Latest Trick (anchor tag) Pseudo Banner Link. This CSS code maker (code generator) outputs a ‘ …

Source

CSS Help

FCKeditor - How to define Anchor tag in .xml and .css file

… an own CSS in Fck editor and how to intgrate it. and how to define anchor tag inside an css … how to define anchor tag inside xml file and css file. …

Source

CSS Help