Introduction
On my site I use a variety of JavaScripts to enhance user experience. Here I provide some of the more generic and useful scripts.
Larger images
Often you have a number of small images on a page, but you want to provide the readers with the large version if they should want to see it. You can simply add a link to the large image, or, if you are lazy like me, you use this script.
The only preparation required is that you place all small images in a directory names small and the large versions in a directory named large, the script does the rest.
JavaScript
All images that are in the small directory are given an onclick handler, that simply takes the current url of the image, substitutes "large" for "small" and redirects the browser to the location of the larger image.
function getBigImage() {
window.location = this.src.replace(/small/,"large")
}
function prepareBigImage() {
var images = document.getElementsByTagName('img');
for(var i=0; i<images.length;i++) {
var srcvalue = images[i].src;
if(srcvalue.indexOf('small/') != -1) {
images[i].onclick = getBigImage;
images[i].className += ' bigger';
images[i].title = 'Click here for a larger image.';
}
}
}
CSS code
img.bigger { cursor:pointer; }
Automatic favicons with links
The original idea for this technique comes from the CSS guy. The script loads the favicons of links to external sites, and by placing the favicon behind the link it provides a visual cue to the user. I rewrote the script for my purposes, and made it a bit more flexible and robust in the process.
JavaScript code
The script only considers <a> elements within id="content", and the favicons are only loaded for links to external sites (links that start with http: and do not contain www.markschenk.com) and if the favicon cannot be loaded, a generic image is loaded.
function faviconize(){
var links = document.getElementById('content').getElementsByTagName('a');
for (var i=0; i<links.length; i++) {
var link = links[i];
setFavicon(link);
}
}
function setFavicon(link) {
var hrefvalue = link.getAttribute("href");
if (hrefvalue && hrefvalue.match(/^http:/) && !hrefvalue.match(/www\.markschenk\.com/)) // check whether external link
{
var domain = hrefvalue.match(/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/);
domain = RegExp.$2;
var fav = document.createElement("img");
fav.className = " faviconimg";
var favsrc = "http://" + domain + "/favicon.ico";
fav.setAttribute("src",favsrc);
fav.setAttribute("alt","Favicon of " + domain);
fav.onerror = function () {
this.src = "http://www.markschenk.com/images/icons/icon_external.png";
this.setAttribute("alt","External link");
}
link.appendChild(fav);
}
}
CSS code
When a page has many external links, the effect of many (colourful) favicons can be visually overwhelming. By adding an opacity to the images, this is toned down a bit.
img.faviconimg {
max-width: 15px;
margin-left: 2px;
border-width: 0px;
vertical-align: top;
opacity: 0.5;
}
a:hover img.faviconimg { opacity:1; }