SIDEBAR
»
S
I
D
E
B
A
R
«
Use JavaScript To Dynamically Display Images
May 31st, 2009 by Michael McKennedy

Article | Use JavaScript To Dynamically Display Images | May 2009 | M.McKennedy

JavaScript can be used to dynamically display images on a single web page based on the anchor tag in the URL.  Why? Because I didn’t feel like creating a separate page for each image – especially since I post 1 image every single day (and have been doing this since January of 2008).  Sure it would have been simple to create a template and then find/replace certain elements of the page to account for the date change but that’s not as much fun as trying to figure it out using JavaScript.  And yes, I do understand that some users will not have their browser set to use JavaScript that’s why there is a default ‘error’ message.  And no, I do not claim to be an expert of JavaScript.

My Good Friend JavaScript

My Good Friend JavaScript

I wanted to be able to post links to my “Things I Saw” photographs on such social networking sites as Twitter and FaceBook.  The previous method was to post a link such as this http://www.mckennedy.org/photo-galleries/things-i-saw/2009/05/20.jpg the problem here is that all you see is the image, no navigation, no Google Ads, in otherwords there isn’t much of a chance that visitors will explore the other parts of McKennedy.org.   The solution, use JavaScript!

My photographs are stored in directories using this convention: yyyy/mm/dd.jpg (as seen in the URL above).  The .html page I created to hold these images and the JavaScript is called things-i-saw.html.  The new link format is http://www.mckennedy.org/things-i-saw.html#yyyy/mm/dd – (see it in action here).

Step 01: I needed a way to grab the anchor tag (the part that starts with #) from the URL.  Here’s how:

    var urlHash = window.location.hash;
    var imageDate = urlHash.match(/\#(.+)/i); // grab the anchor and everything after
    // from the url

Step 02: Create the image tag url beginning and store it

    var base="<img src='http://www.mckennedy.org/photo-galleries/things-i-saw/";

Step 03: Create the image tag url ending and store it

    var end=".jpg' alt='Things I Saw by Michael McKennedy' />"

Step 04: Remove the # sign from the anchor tag and only use the characters that are needed

    var temp=str.substr(12,10); // grab the image date starting at character 12 and
    // continue 10 characters

Step 05: Capture the date values

    var tempMonth=temp.substr(5,2); // grab the month
    var tempYear=temp.substr(0,4); // grab the year
    var tempDay=temp.substr(8,2); // grab the day

Step 06: Create a page element to hold the image

    <div id="imageHolder"></div>

Step 07: Write the dynamically created image to imageHolder

    document.getElementById('imageHolder').innerHTML = base + temp + end;

Step 08: I wanted to be able to display the correct image date above imageHolder, and have the month display in string form (and test to see if it’s a valid month)

    if (tempMonth == '01') {
	month='January';
    }
    else if (tempMonth == '02') {
	month='February';
    }
    else if (tempMonth == '03') {
	month='March';
    }
    else if (tempMonth == '04') {
	month='April';
    }
    else if (tempMonth == '05') {
	month='May';
    }
    else if (tempMonth == '06') {
	month='June';
    }
    else if (tempMonth == '07') {
	month='July';
    }
    else if (tempMonth == '08') {
        month='August';
    }
    else if (tempMonth == '09') {
        month='September';
    }
    else if (tempMonth == '10') {
        month='October';
    }
    else if (tempMonth == '11') {
	month='November';
    }
    else if (tempMonth == '12') {
	month='December';
    }
    else {
        month='The URL did not contain a valid month';
    }

Step 09: Create a page element to display the newly formatted date

    <span id="date"></span>

Step 10: Write the newly formated date to ‘date’

    fullDate = month + ' ' + tempDay + ',' + ' ' + tempYear; // format the date
    document.getElementById('date').innerHTML = fullDate; // write to 'date'

Step 11: If the URL does not contain an anchor tag, show some default verbiage explaining how the page works.  This was accomplished by entering text into “imageHolder” (which gets overwritten if the anchor tag has a valid date).

    <div id="imageHolder">Default text here</div>

Step 12: Call the JavaScript function as the page is loaded

    <body onLoad="showPhoto();";>

Here is the complete JavaScript function:

<script language="javascript" type="text/javascript">
<!--
function showPhoto()
{
		var month='';
		var year='';
		var day='';
		var fullDate='';
		var urlHash=0;
		var base="<img src='http://www.mckennedy.org/photo-galleries/things-i-saw/";
		var end=".jpg' alt='Things I Saw by Michael McKennedy' />"
		var imageDate=0;
		var urlHash = window.location.hash;
 		var imageDate = urlHash.match(/\#(.+)/i); //grabs the anchor from the url
		var str=imageDate.toString(); // convert to string
		var temp=str.substr(12,10); // grab the image date
		var tempMonth=temp.substr(5,2); // grab the month
		var tempYear=temp.substr(0,4); // grab the year
		var tempDay=temp.substr(8,2); // grab the day
		if (tempMonth == '01') {
			month='January';
		}
		else if (tempMonth == '02') {
			month='February';
		}
		else if (tempMonth == '03') {
			month='March';
		}
		else if (tempMonth == '04') {
			month='April';
		}
		else if (tempMonth == '05') {
			month='May';
		}
		else if (tempMonth == '06') {
			month='June';
		}
		else if (tempMonth == '07') {
			month='July';
		}
		else if (tempMonth == '08') {
			month='August';
		}
		else if (tempMonth == '09') {
			month='September';
		}
		else if (tempMonth == '10') {
			month='October';
		}
		else if (tempMonth == '11') {
			month='November';
		}
		else if (tempMonth == '12') {
			month='December';
		}
		else {
			month='The URL did not contain a valid month';
		}
		fullDate = month + ' ' + tempDay + ',' + ' ' + tempYear;
		document.getElementById('date').innerHTML = fullDate;
 		document.getElementById('imageHolder').innerHTML = base + temp + end;
}
//-->
</script>

One minor issue with this is that if a user visits the URL and they want to view another photograph from a different date they have to edit the URL to use the new date, then refresh the page to view the new image.  I am ok with this since this page is not meant as a way to view all of the “Things I Saw” Photo Gallery images, as there is a gallery page to do that already.

Here is a working example of things-i-saw.html in action

Here is an example without the anchor tag in the URL

Right click and ‘view page source’ to see how this works.

This code has been testing in FireFox 3.0.10, Internet Explorer 8, Google Chrome 1.0.154.65, Safari (for Windows) 3.2.2 and Opera 9.5.1

Footnote: I am sure that there are other ways to accomplish this same thing, maybe even better ways but I have not figured them out yet.  I am sort of a JavaScript beginner and do not claim by any means to be an expert in the subject but I sure do have fun playing with JavaScript.
JavaScript onMouseOver Link -> Change Div’s Background-Image
Feb 25th, 2009 by Michael McKennedy

Article | HTML/JavaScript Tutorial | Feb 2009 | M.McKennedy

So you want to know how to change a background image when a link is hovered over and back to the original onMouseOut but you don’t know much HTML and/or JavaScript?  Perfect… take a look at this simple tutorial on how to use the Document Object Model (DOM), the onMouseOver and onMouseOut event handlers and a bit of JavaScript to make the magic happen.

Now before I jump into this I must say.  I am not an expert in JavaScript nor HTML but I was bored today so I decided that I wanted to create a “onMouseOver” event to trigger the background image of a Div to display add odd image of myself (this is for my personal website of course, and all in good fun) when my name is hovered over with the mouse pointer. I wanted the image to appear as the background while keeping the text of the paragraph “on top” of the image, so it has looks like I am trapped beneath the text, yes, I know…not the most appropriate use of my time but it was enjoyable. As the mouse pointer is moved from the link the image goes back to a white background.

I do understand that there are many different ways to achieve this same effect.  Some “better” than others.  So if you have come here to add snotty comments about crappy HTML, JavaScript or CSS coding then you should just leave now.  (Well, of course you can stay and read on…just don’t leave any negative feedback unless you have something constructive to go with it.  If you know of other ways to achieve the image roll over effect then please feel free to post and post often!

I searched various forums and found plenty of different methods posted by a variety of different skill leveled authors but none that suited my “copy and paste” desires.  There were a host of HTML tutorials on how to change the background color when a link was clicked.  Tons of posts where the subject of the post and/or article was lost in a blur of childish bickering over coding semantics.   I was looking for a quick and easy way so I reworked my search term and entered them over and over into the almighty Google to no avail.  I needed to dig in to find out how it all worked so I changed my search terms to “HTML Document Object Model “.   If I was going to do this I needed to learn about how HTML page elements can be accessed and therefore manipulated.

Eventually I stumbled upon (and in hindsight should have been the first place I looked)  http://www.w3schools.com/ and specifically their section on the HTML Document Object Model – http://www.w3schools.com/htmldom/default.aspI was able to figure it out and it’s really quite simple.  Here is a link to what I did – hover your mouse over the word Michael in the first paragraph to watch the image appear. Move your mouse pointer away from the link to watch the background return to white.

Below are two static images of what happens with the mouse over, click on them for a larger view or just go to McKennedy.org and see it for yourself.

Moving the mouse pointer over the word Michael creates triggers the onMouseOver event. (click for a larger view)

Hover Over This Link To Change The Div's Background Image (click for larger view)

The onMouseOver Event triggers the changing of the divs background image. (click for a larger view)

Hovering Over The Link Causes The onMouseOver Event To Change The Background Image Of The Div

If you want to practice this on your own here are links to the two images:

Michael
Spacer

Here is how I did it.

<html><title></title><body><head>I put following section between the head tags  – like this</head><body></html> tags:

<!– Image Roll –>
<script type=”text/javascript”>
function changeStyle()
{
document.getElementById(“imageRoll”).style.backgroundImage=”url(images/profile/from-above-thumbs-up.jpg)”;
}
function changeStyleBack()
{
document.getElementById(“imageRoll”).style.backgroundImage=”url(images/spacer-2×2-white.jpg)”;
}
</script>
<!– End Image Roll –>

The Div that changes background when the link is hovered over is below:  This belongs somewhere between the <body></body> tags.

<div id=”imageRoll” style=”background-repeat:no-repeat”>

<p style=”font-size: 1.2em”>Some Opening Title – Something BOLD – Eye Grabbing</p>

<p>Here is where I write some text, yes, some text and then I put some more and try to use words that are more than five characters.  My name is <a href=”#” onmouseover=”changeStyle()”; onmouseout=”changeStyleBack()” title=”Michael Gives Two Thumbs Up To His Own Web Site>Michael</a>,

and if this code was live then when you hovered over the word “Michael” you would have seen an image of me appear beneath this text.</p>

</div>

To put the entire thing together:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>onMouseOver Change Div Background Image Example</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<!– Image Roll Over Code –>
<script type=”text/javascript”>
function changeStyle()
{
document.getElementById(“imageRoll”).style.backgroundImage=”url(images/profile/from-above-thumbs-up.jpg)”;
}

function changeStyleBack()
{
document.getElementById(“imageRoll”).style.backgroundImage=”url(images/spacer-2×2-white.jpg)”;
}
</script>
</head>
<body>
<div id=”imageRoll” style=”background-repeat:no-repeat; width:348px; height:261px”>
<p style=”font-size: 1.2em”>Some Opening Title – Something BOLD – Eye Grabbing</p>
<p>Here is where I write some text, yes, some text and then I put some more
and try to use words that are more than five characters. My name is <a href=”#” onmouseover=”changeStyle()” onmouseout=”changeStyleBack()” title=”Michael Gives Two Thumbs Up To His Own Web Site”>Michael</a>,
and if this code was live then when you hovered over the word &quot;Michael&quot; you
would have seen an image of me appear beneath this text.</p>
<p>I set the height in the style of this div because this text wasn’t filling
the space to allow the entire background image to appear when the link is
hovered over.</p>
</div>
</body>
</html>

The code above is valid XHTML Transitional 1.0.  and has been tested in Firefox 3.0.6, IE 7, Google Chrome, Opera 9.2, and Safari (For Windows) 3.2.1.

I thought about pre-loading the image using JavaScript or CSS but then I realized that the image itself is only 18.9 KB therefore there should not be much time spent waiting for the background image to load.

So there it is…and it’s pretty simple too.  A short and sweet way to solve the big JavaScript onMouseOver onMouseOut Background-Image changing mystery.  Copy, Paste and modify the above code to fit your needs.

An Old Client Comes Back | Vermont Discovery Cruises | Website Design
Feb 24th, 2009 by Michael McKennedy

Website Design | February 2009 | M.McKennedy
The Old Moonlight Lady Website

The 'Old' Moonlight Lady Website

Back in 2007 I was hired to design a custom website for The Moonlight Lady which offers New England vacation cruises based out of Lake Champlain in Burlington, Vermont.  The original site had a unique, rustic look (as does the boat the Moonlight Lady) and used tabs, and hidden divs to keep users from leaving a page.   As a matter of fact nearly every page had it’s only Contact Us section – the idea was to give users a simple way to get more information about the cruises offered which helps covert these users into leads.  There was a bit of the web 2.0 look and feel to the site.

Several months after the Moonlight Lady website went live I was informed that there was a new project manager working for the Moonlight Lady and that she wanted to take their services to a bigger company – one who specialized in hotel and tourism websites.  They were looking to simplify the website.  I wished them the best of luck.

Vermont Discovery Cruises - The New Site

Vermont Discovery Cruises - The 'New' Site

A year later and the Moonlight Lady is back!  I was contacted back in December of 2008 about the possibility of taking over the existing Vermont Discovery Cruises website.  I looked over the template created by this other company and saw the possibly of greatly improving the site without deconstructing it.  One of the first things I changed was to convert the Flash-based slide shows to something a bit more search-engine-friendly.  I switched them to html/javascript slide shows.  Also, one of the most obvious changes was that the site need to use title tags on all links – this is basic SEO (search engine optimization)!  I was also tasked with adding new tours complete with custom graphics and stock photography, as well as customized Google maps for each cruise route.

New cruise tours have been added and lots of clutter has been removed.  When the client needs something added/changed and/or modified I get things done in a day or two – depending on the priority (as opposed to the rumored three weeks it was taking the other company).  I provide a high level of service that keeps my oldest clients (it’s been over 8 years now since I signed my first client) around and through word of mouth keeps new clients coming in.

The Moonlight Lady was the first client to leave me for my website design services and now they are back!  Vermont Discovery Cruises offers a variety of overnight vacation cruises throughout New England and Canada.  Take a cruise on the Moonlight Lady – as they say Relax, Refresh, Recharge, Connect on board this unique Lake Champlain vacation!

Horizontal Sliding JavaScript Menu Highlighter – Sweet!
Jan 3rd, 2009 by Michael McKennedy

HTML – JavaScript – CSS | Jan 2009 | M.McKennedy

I stumbled upon this lightweight (1kb) horizontal sliding JavaScript menu highlighter yesterday – simple to implement, cross-browser compatible and free!  This morning I replaced the existing navigation on McKennedy.org with this sweet-looking version from www.leigeber.com.

McKennedy.org got a make-over this morning which bumped up the site version from 2.0 to 3.0.  I replaced the navigation with a nifty sliding JavaScript menu highlighter.  The old navigation was a bit boring.  The coding was fine and lightweight and relied on CSS using background images but really there wasn’t any flare – at all!  Now that I look back at it I am wondering, “what the hell was I thinking?”

2008 Navigation on McKennedy.org

2008 Navigation on McKennedy.org

The new sliding JavaScript menu highlighter is pretty slick. On mouseover the highlighting “slides” over the where the mouse pointer was and then slides back to it’s original place. It’s very cool!

2009 Navigation on McKennedy.org

2009 Navigation on McKennedy.org

The original sliding JavaScript menu highlighter script can be found here.  To implement the new navigation was really simple.

<div class="menu">
    <ul id="menu">
        <li><a href="some-web-page.html" title="Some Web Page">Web Page 1</a></li>
        <li><a href="some-web-page-2.html" title="Some Web Page">Web Page 2</a></li>
        <li><a href="some-web-page-3.html" title="Some Web Page">Web Page 3</a></li>
        <li value="1"><a href="some-web-page-4.html" title="Some Web Page">Web Page 3</a></li>
    </ul>
    <div id="slide"></div>
</div>

To set the default menu item use this sytax value=”1″ (as seen above).

The CSS side of it consists of a mere 6 lines which I adjusted below for formatting reasons:

 {
margin:0; padding:0;
}

.menuSlide {
position:relative;
background-color:#000000;
height:35px;
width:100%;
}

.menuSlide ul {
list-style:none;
z-index:10;
position:absolute;
z-index:100;
padding:9px 5px;
}

.menuSlide li {
float:left;
}

.menuSlide a, .menuSlide a:active, .menuSlide a:visited, .menuSlide a:hover {
text-decoration:none;
color:#FFF; padding:10px;
}

#slide {
position:absolute;
top:6px;
height:24px;
background:#ffcc33;
z-index:10;
}

The JavaScript (which is a bit advanced for me) side of things is also somewhat compact. I made a few formatting changes below so the code will fit on this page.

var menuSlider=function(){
	var m,e,g,s,q,i; e=[]; q=8; i=8;
	return{
		init:function(j,k){
			m=document.getElementById(j);
                        e=m.getElementsByTagName('li');
			var i,l,w,p; i=0; l=e.length;
			for(i;i<l;i++){
				var c,v; c=e[i];
                                v=c.value;
if(v==1){s=c; w=c.offsetWidth; p=c.offsetLeft}
				c.onmouseover=function(){menuSlider.mo(this)};
                                c.onmouseout=function(){menuSlider.mo(s)};
			}
			g=document.getElementById(k);
                        g.style.width=w+'px';
                        g.style.left=p+'px';
		},
		mo:function(d){
			clearInterval(m.tm);
			var el,ew;
                        el=parseInt(d.offsetLeft);
                        ew=parseInt(d.offsetWidth);
			m.tm=setInterval(function(){menuSlider.mv(el,ew)},i);
		},
		mv:function(el,ew){
			var l,w; l=parseInt(g.offsetLeft);
                        w=parseInt(g.offsetWidth);
			if(l!=el||w!=ew){
				if(l!=el){var ld,lr,li; ld=(l>el)?-1:1;
                                lr=Math.abs(el-l); li=(lr<q)?ld*lr:ld*q;
                                g.style.left=(l+li)+'px'}
				if(w!=ew){var wd,wr,wi; wd=(w>ew)?-1:1;
wr=Math.abs(ew-w); wi=(wr<q)?wd*wr:wd*q; g.style.width=(w+wi)+'px'}
			}else{clearInterval(m.tm)}
}};}();

To initialize the script simply call the function:

menuSlider.init('menu','slide')

For example:

<body onload="menuSlider.init('menuSlide','slide')">

To see this in action go to McKennedy.org.

To download the script from the original source and to check out more of what Mr. Leigeber has to offer (free for both personal and commercial use) go here.

I have personally tested this in the follow web browsers and did not find any issues:

  • Firefox – v 3.0.5
  • Google Chrome – v 1.0.154.36
  • Internet Explorer – v 7.0
  • Safari (for Windows) – v 3.2.1
  • Opera – v 9.51

Thanks Mr. Leigeber!

Photography and other stuff....
© Michael McKennedy | McKennedy.Org