CodeinWP CodeinWP

How to Dynamically Highlight Content Like Wikipedia Using CSS3

Dynamically Highlighting FootnotesIf you’ve ever clicked on a footnote link in a Wikipedia article, you’ve probably noticed that two things happen: (1) the link brings you to the footnote section at the bottom of the page; and (2) the selected footnote is highlighted with a different color. In a list of footnotes, this feature makes it easy for the reader to visually access the appropriate footnote.

This is a neat little technique that is accomplished easily using the CSS3 :target pseudo-class selector. Unfortunately, this is another CSS3 feature that has no support in Internet Explorer, and so has been largely overlooked up to this point.

In this brief tutorial, I’ll show you how it’s used, and also provide a quick little JavaScript solution that can be added to an IE-only external script to get it to work cross-browser. IE (all three versions) is the only browser that fails to offer support for this very practical CSS3 feature.

Wikipedia’s Use of the :target Pseudo-Class

In the two screenshots below from the Cascading Style Sheets Wikipedia entry, you can see how it works:

Footnote on Wikipedia
When the footnote is clicked…

Footnote Selected
…the screen is scrolled to the bottom, and the selected footnote is highlighted in blue.

A Simple Demonstration

Take a look at the following demo page, which is a mock article that doesn’t use the :target pseudo-class selector. The linked footnotes found in the first five paragraphs bring the reader to the bottom of the page. If the reader isn’t paying close attention to the number of the footnote that was clicked, he may not immediately know which footnote to read. This is especially true on a site like Wikipedia that often has dozens of footnotes on each entry.

View the demo without the :target feature implemented

Now view the same page with the following CSS added, using any browser except Internet Explorer:

:target {
  background: #ccc;
  border: solid 1px #aaa;
}

View the demo with :target added

Now when a footnote is clicked, the “targetted” footnoted is highlighted with a grey background and border color, helping the reader see exactly which footnote was clicked. This feature even makes use of the back button by removing the highlight when the back button is used. And of course, you can deep link to a footnote from an external page and the appropriate section will be highlighted the same way. As you can see, the :target attribute is very practical and intuitive, making a nice addition to the new CSS3 selectors.

Coding a Solution for Internet Explorer

Achieving the same effect for IE is pretty simple. It will not have the added back button functionality, but it will deep link. The jQuery/JavaScript checks to see if a fragment identifier (i.e. “hash”) exists in the URI, or has been clicked, and highlights the appropriate section accordingly.

The code will add the following CSS to the appropriate element:

.customTarget {
  background: #ccc;
  border: solid 1px #aaa;
}

The CSS above is the same as that given to the :target attribute. Now here is the JavaScript:

$(function() {

  $("li").removeClass("customTarget");
  var myLocation = document.location.hash.replace("#","");
  if (myLocation) {
    document.getElementById(myLocation).className = "customTarget";
  }

  $("a").click(function () {
    $("li").removeClass("customTarget");
    var clickedLink = this.href.split("#");
    if (clickedLink.length > 1) {
      document.getElementById(clickedLink[1]).className = "customTarget";
    }
  });

});

The JavaScript code will add a class name to a list item that has an id that’s equal to the clicked (or deep-linked) hash value.

Here is a rundown of the code:

  • Line 3 removes any existing classes that have the highlight in place
  • Lines 4-7 get the current “hash” value, then, if the hash exists, changes the class name of the matching element; this is the part of the code that allows “deep linking” from another page
  • Lines 9-15 add a click event to all anchors on the page, doing essentially the same thing that was done when deep-linking in lines 4-7, including removing the “customTarget” class to ensure only one footnote is highlighted at any one time; this time the “hash” is accessed from the href value of the clicked anchor

This code could be added to any page where the :target pseudo-class selector needs to be mimicked for Internet Explorer. The only parts that might need modification are lines 3 and 10, which specifically target <li> elements. If your code uses <div> elements, for example, then you would change it accordingly.

Just place the code inside of IE-only conditional comments, and you’ve got a virtually cross-browser solution for the :target pseudo-class selector that works roughly the same way as the footnote area on Wikipedia.

18 Responses

  1. Jae Xavier says:

    Nice post.

    This makes posting footnotes and citing source much similar to the standards of writing. Gotta love CSS3 but a boo for Internet Exploder.

  2. BigM75 says:

    thats a good think, nice

  3. Ted Goas says:

    I never knew this effect was this simple!

  4. Dana Elza says:

    It works, it really works! Thank you.

  5. Steve R says:

    Interestingly both with IE8 and Firefox if I click a footnote, the page repositions, then I use the mouse wheel to return to the top and click another footnote. Sometimes it only scrolls half-way down the page, sometimes it works as expected.

    Don’t see the bug if I use the scroll bar to return to the top.

  6. Beben says:

    This may be a little conflict with existing css code. Such as h1, h2, h3, ul, ol … we just a little outsmart this trick
    This trick is good …. thanks for share

  7. Web Risorsa says:

    Nowadays everybody is trying to attract the visitors in some way by the concept or the new techniques in CSS or any other…
    This is of the same kind and it’s useful for most of the websites…

  8. wow it is so simple, i will use it in one of my projects, thanks for the info

  9. ASAD ULLAH says:

    wow. how simple this effect. thanks for informing.

  10. webman says:

    Ok let me try that again – I’m in spastic mode today.

    Does anyone know how I dynamically highlight content on another page? I tried this link: page.html/#one
    It worked locally but not live.
    Any ideas

    Thanks in advance

    • webman says:

      Please ignore me everyone I just realised the error of my ways.
      Just took out the “/” so the link is now “page.htm#one”.

      Sorry for wasting your time.

      Thanks for sharing the code its great.

      • Actually, I was just about to test what you said, to see why you were having problems. I didn’t notice the slash before the hash. Anyhow, glad you got it to work.

  11. Ronald says:

    Thanks a lot, I was looking for this solution to show some content folder in my website. You are the best.

  12. This is a really nice tutorial. This should help out a lot. Thanks for sharing.

  13. Werner says:

    it is also:
    all links on same page

    
    // :target inside document
                  $('a.target').click(function() {
                     var id = $(this).attr('href');
                     $('h3').removeClass('ieTarget');
                     $(id).addClass('ieTarget');
                  });
    

    all links to another page

    
    // :target other document
                  if(document.location.hash) {
                     $(document.location.hash.replace()
                     ).addClass('ieTarget');
                  }
    

    Greetings Werner

  14. hcr says:

    Hi
    I am searching for css that does footnoting automatically when printing
    thanks

  15. Diseño Web says:

    This trick is excellent …. thanks for share with us!

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).