ieatpenguin

September 30, 2009

Emulating target=”_blank” in XHTML

Filed under: Javascript — Russell @ 3:00 pm

A friend was having trouble with this earlier today so thought I’d post the answer. Whether or not you consider this cheating (I don’t), it’s the only way to get a link to open in a new window and remain valid XHTML code, and be valid in the upcoming XHTML 4.0. It is still valid in XHTML 1.0.

The reason this was taken out in XHTML 4.0, is that the W3 see a new window as no longer being the concern of the current document – and so not valid XHTML, as therein lies the language’s concern.

Anyway, to the solution, a simple bit of Javascript:

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

Place this in a .js file along with the rest of your .html files, and then call it in the head of the document thus:

<script type="text/javascript" src="xhtmllinks.js"></script>

And then edit your links to call the script every time they are clicked:

<a href="http://www.r-dunn.co.uk/ieatpenguin/" rel="external">i eat penguin</a>

June 9, 2009

Using different CSS styles in Javascript enabled browsers

Filed under: Javascript — Russell @ 12:58 pm

This is an easy to implement, yet useful and possibly powerful technique. Using different CSS rules in JavaScript enabled browsers lets you customise your website styles for JS enabled and disabled browsers using only CSS.

Thus: you leave the concerns of styling strictly to CSS, and the business aspect of the website to the javascript.

All you need to do is to add some class or id to body element using JavaScript to specify that JavaScript is available. Then define two rules in your CSS file(s) for JS enabled and disabled browsers.

Here is an example for a JavaScript enabled browser:

document.getElementsByTagName("body")[0].setAttribute("class", "js");

And in your CSS file:

.aClass{
    display:block;
}
.js .aClass{
    display:none;
}

Why do I need to have a different CSS styles for jQuery enabled browser you might ask. Well, consider you have a drop-down menu on your website’s sidebar and you would like to use Javascript to make it drop down on mouse hover. This would render the element not accessible if the user has disabled Javascript on his/her browsers.

Powered by WordPress