Click here to Skip to main content
15,880,796 members
Articles / Web Development / HTML

JavaScript Principles - Creating an Image Browser and Understanding its Principles

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
20 Nov 2009CPOL13 min read 20.5K   11   8
An article about creating an Image Browser and understanding its principles

Introduction

First of all, this article is aimed towards beginners in programming, those who wish to learn something in a simple way, explained from the ideas of the project to the programming and execution of this project.

In this article, I will provide some data that I would have liked to have had while I was a beginner myself, instead of going through sh*t-loads of code (which I could barely understand) from which I extracted bits of information to develop my own ways of doing stuff. So this article’s intent is to explain every bit of information it contains.

Having that out of my chest, let’s get started, shall we?

Alright, so you decided to create a web image browser for your site using JavaScript, but why? Couldn’t you just create an image browser in HTML, with the knowledge you acquire studying it for about 10 minutes? Well, yes, you could… but you shouldn’t. Why? Well, if you use HTML only to create your image browser, you will need one HTML file for each of your images, which means that you will need 1 page for each of your images. That is bad, very bad. Let’s say that you have a gallery which contains about 100 images. Using only HTML, you would need 100 pages to display that. This is not an efficient way of doing this. Instead, why not have some simple lines of code that deal with your image browsing issues for you? Seems better, quicker, smarter, heh? This is where JavaScript comes and takes care of this job.

Now, before actually going into the JavaScript itself, we need to cover up some basics steps, like what we need and why we need it.

Well, this is an image browser, so we’ll need images. We also need some way to browse through those images, so we need a simple menu (containing functions like “previous” and “next”). You don’t actually need this, but a simple search feature would be nice. So, here is our list of “what we need”:

  • Images
  • Menu to browse
  • Search engine (not mandatory, but nice to have)

Okay, so we got our list ready, so we know everything we want; now we just got to do it!

Before getting into the whole JavaScript file, we will need to get into the HTML file, because that’s the one that will show our images. I will put the script here and explain it.

Here it is, the HTML file:

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>
			Blahblah
		</title>
	<script type="text/javascript" src="myjava.js"></script>
	</head>
	<body onload="startup()">
		<div>
			<img src="image19.jpg" id="imagenumber" alt="image"/>
			<div>
				<ul>
					<li><a class="latest"
					href="javascript:imgbrowser
					(imagemax)">latest</a></li>
					<li><a class="next"
					href="javascript:imgcalcadd()">next</a></li>
					<li><a class="previous"
					href="javascript:imgcalcsub()">
						previous</a></li>
					<li><a class="first"
					href="javascript:imgbrowser(1)">
						first</a></li>
				</ul>
			</div>
			<span id="x"></span>
			<form>
				Go to page:
				<input type="text" size="1" maxlength="3"
					id="pagesearch" onkeypress="return
						noletters(event)"/>
				<a href="javascript:search()">GO!</a>
			</form>
		</div>
	</body>
</html>

Let’s explain this, bit by bit. First there is the tag. This tag defines to your browser how to read your code. There are several options for HTML formatting, which are available here: I used XHTML 1.0 Strict since I like it better, because it forces good practices while scripting.

Now the basic tags. Inside this one, we’ll put our JavaScript file, the title of our page and (if you have one or want one) the CSS file for styling your page. In this article, we will not cover the CSS part, but maybe in the future. For the purpose of this article, this line is very important:

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

Here we declare that this is a script, a JavaScript and declare the source of it. If you want, you don’t have to provide the source of the JavaScript, but in this case you’ll need to insert the code inside the script tags, which would look like this:

HTML
<script type="text/javascript">
		… your code here …</script>

This is what we call embedded code, meaning that your script is inside the HTML file, so it does not require external code.

NOTE: The scripts can be inside the tags or outside the tags. I prefer the first one, but it is your call in the end. This principle applies only to embedded code. If you use external JavaScript the <script> tag containing the source for it must be inside the tags.

Now for the body tag. You may have noticed something different there, let’s write it again:

HTML
<body onload="startup()">
		… blah blah blah …</body>

So… what the hell is up with that onload=”startup()” crap? Well, this will be explained after the JavaScript part of this article, so we’ll just leave this for now. All we need to know is that this makes something happen when the page loads.

The <div> tag is there to divide the page in parts. This is a tableless design, which means we won’t use <table> to separate and organize the content of our page. This is better, easier and cleaner, it is a good practice to use tableless design for your web pages.

The <img> tag is now up, and it is a very important part of our image browser. Here, let’s re-write the line:

XML
<img id="imagenumber" alt="image" src="image19.jpg" />

Now, this means that this is an image (duh… really?), that the source (the image it will display) is “image19.jpg” (this can be whatever you want, this seems obvious but doesn’t hurt to say it. The reason for it to be 19 will be explained later), that the id of this image is “imagenumber” (this is what will identify this particular image in the script that is yet to come, this can also be named whatever the hell you want) and that if the browser cannot load the image for some reason or while it is loading it, the word “image” will display where the image should be (you can also make any word you want appear instead of “image” if you want). Now there is another <div> tag, this will contain our menu. The <ul> tag means unordered list, which means that this list is not numbered. Inside the <ul> tag, there are the <li> tags which are the list items. In this list items there are the links or <a> (anchor) tags. It is inside the <a> tags that the functions in our JavaScript are called. Let’s take a look:

JavaScript
<li><a href="javascript:imgbrowser(imagemax)">latest</a></li>

This basically says that this list item contains an anchor that refers to something (in this case, the function call). Inside that “href” part is where you put what your anchor does, if it simply takes to a web site you simply insert the address there (like “href=www.codeproject.com”, this will take you to the CodeProject site if you click on this anchor), in this case is where we put our function calls. Now there is the tag. This tag is very useful because it is like a blank tag, which you can add any proprieties that you want. You want to have 7 kinds of bold text in your page? Using the tag combined with CSS, this is easily achievable. In this case, the tag is where the number of the image will be displayed. The “id=x” is to identify it in the JavaScript that is to come. Now there is a simple <form> tag that contains our search feature. Let’s take a look at it:

HTML
<form>
Go to page:
<input type="text" size="1" maxlength="3" id="pagesearch" 
	onkeypress="return noletters(event)"/>
<a href="javascript:search()">GO!</a></form>

Now, what do we have here? In this form, there is a simple text box with the id “pagesearch”. When you press a key in your keyboard, the “onkeypress” occurs and the function “noletters” is called, returning only what the function wants to display to you (or what it returns to you). There is also a tag containing the function that searches your gallery.

Alright, the HTML was covered! Quite simple, huh? This page displays only the image, the image number and the browse menu, but you could add whatever you want to it if you like.

Now, it is time for us to take a look at our JavaScript file! Just so you now, the JavaScript file name is “myjava.js”.

Here it is:

JavaScript
var imagenumber=19;
var imagemax=imagenumber;

function startup()
	{
	document.getElementById('x').innerHTML=imagenumber;
	}

function imgcalcsub()
	{
	imagenumber=document.getElementById('x').innerHTML;
	imgbrowser(imagenumber -1)
	}

function imgcalcadd() //next option
	{
	imagenumber=document.getElementById('x').innerHTML;
	imgbrowser(imagenumber -[-1])
	}

function search()
	{
	imagenumber=document.getElementById('pagesearch');
	if(imagenumber.value>imagemax)
		{
		window.alert('This page does not exist, at least for now. 
			Please, try another page.');
		}
	else
		{
		imgbrowser(imagenumber.value)
		}
	}

function noletters(e)
	{
	var keynum;
	var keychar;
	var numcheck;

	if(window.event)
		{
		keynum = e.keyCode;
		}
	else if(e.which)
		{
		keynum = e.which;
		}
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	if(keynum==8 || keynum==null)
		{
		return true;
		}
	else
		{
		return numcheck.test(keychar);
		}
	}

image = new Image();
image.src = "";

function imgbrowser(imagenumber)
{
if(imagenumber<1){var imagenumber=1;}

if(imagenumber>imagemax){var imagenumber=imagemax;}

document.getElementById('x').innerHTML=imagenumber;

var image = new Array();
image[0] = "MMORPG-Page";
image[1] = Math.abs(imagenumber);
image[2] = ".jpg";

var currentimage = image[0] + image[1] + image[2];

image.src = currentimage;

document.images['imagenumber'].src=image.src;
}

Now, let’s take a go through this one step at a time. First, we declare the variables. In this image browser, we are first displaying the last image of our collection. The intent of this browser is to display something like comics, where the latest image is the first you see. In this case, the variable “imagenumber” is the same as the latest image, which is 19. If you want to display the first image of your collection, change this to 1 and the source in the <img> tag to “image1.jpg”. But in this case, the “imagemax” will have to be changed to a number (if your gallery has 10 images, it will be 10, if it has 8 images, it will be 8). Now we got the “startup” function. This will begin the process of numbering your pages. It happens only when the page is loaded. This line is what gets the page number:

JavaScript
document.getElementById('x').innerHTML=imagenumber;

This means that the element with the id “x” will display the contents of the “imagenumber” variable. The “innerHTML” allows you to change the text in your HTML file from inside your JavaScript without much hassle. Next we got the image calculation functions, which are “imgcalcsub” and “imgcalcadd”. Let’s look inside it:

JavaScript
imagenumber=document.getElementById('x').innerHTML;
imgbrowser(imagenumber -1)

This process gets the image number from the tag (the one with the “x” id, remember?) for inner calculations. After that it calls another function with the parameters “imagenumber -1”, which means that the current image number -1 will be the number of our next image (in this case, previous, but you get the point). The process in the “imgcalcadd” is exactly the same, the only difference is this line:

JavaScript
Imgbrowser(imagenumber-[-1])

Now, why the “-[-1]” instead of “+1”? Well, because God knows why, JavaScript will not add to the value you want if you use “+” in it. Instead of 1+1=2, it is 1+1=11. The way I choose to deal with this is the double “-“, which is a “+”.

Now for our search feature. This searches for numbers of your images, like pages in a comic book (remember that this browser was made for something like that?), so remember to put numbers in your images names (like “image1”). This function gets the number you typed in and makes the “imagenumber” get that value. After that, it sees if your gallery goes as far as that number, if it does, you will get to the image you need, if it doesn’t, you get a warning saying what the error was. If the image with that number exists, then this line of code will run:
JavaScript
imgbrowser(imagenumber.value)

This means that the function “imgbrowser” will be called (just like in the “imgcalcsub” and “imgcalcadd” functions) but the parameters will be the number you wrote in the text box. The reason behind the “.value” we put there is because everything you write is treated as a string (meaning text). If you ask a function that deals with numbers to deal with a string, it will result in an error. That is why we use the “.value”, that will convert our string into a number (you type 8, the value is 8).

Now if this only deals with number, what will happen if someone tries to search for a text, like “karplak”? Well, this will result in an error, because the page “karplak” does not exist, so there will be no image changes and the browsing will not be possible, because “karplak” (a string) -/+ a number will be an invalid operation. Crap, so this browser depends on the user just writing numbers? Well, this is where we put something to check if our user is writing numbers or letters. The function “noletters” is called whenever you press a key in your keyboard while you’re in the page focusing on the text box. This will get the key you pressed, see if it is a number or a letter and, based on that, will return you something in the text box or not.

JavaScript
if(window.event)
{
keynum = e.keyCode;
}
This is for Internet Explorer benefit.
if(e.which)
{
keynum = e.which;
}

This is for Mozilla, Netscape, Opera, and so on.

These processes will get which key you pressed and store that in a variable named “keynum”. This will store the number of the key, not the key value. For instance, the key “1” is the key number “49”.

JavaScript
keychar = String.fromCharCode(keynum);

This will get the actual value of the key. For instance, we pressed 1, the key number is 49, but the “keychar” will get the value of this key, which is 1. If we pressed the key , the key number is 39, but the “keychar” will get the value .

JavaScript
numcheck = /\d/;

This line will check for single digit numbers inside what you wrote. It detects only numbers.

JavaScript
if(keynum==8 || keynum==null)
		{
		return true;
		}
	else
		{
		return numcheck.test(keychar);
		}
	}

The if(…) part ensures that keys such as arrows, delete and backspace are accepted, even though they are not numbers.

The else part returns what the “numcheck” detected as numbers, and only that. Now we get the image displaying part of the JavaScript.

JavaScript
image = new Image();
image.src = "";

This declares a new object called “image” and declares its source (in the case, nothing).

The function “imgbrowser” is defined next. This function will check if the “imagenumber” exceeds the “imagemax” or if it is below “1”. This will also be responsible for displaying the images.

JavaScript
if(imagenumber<1){var imagenumber=1;}

This makes sure that if the “imagenumber” is less than 1, the “imagenumber” will have its value set to “1”.

JavaScript
if(imagenumber>imagemax){var imagenumber=imagemax;}

This makes sure you cannot go beyond the extent of your gallery. If you exceed the “imagemax”, your “imagenumber” will have its value set to the same value as the “imagemax”.

JavaScript
document.getElementById('x').innerHTML=imagenumber;

This will update the image number displayed for the user.

JavaScript
var image = new Array();
image[0] = "image";
image[1] = Math.abs(imagenumber);
image[2] = ".jpg";

var currentimage = image[0] + image[1] + image[2];

image.src = currentimage;

This will name our images. In this case, our image name is “image[number].[extention]”. You could use 3 variables to do this, but I don’t see why. I used only one and established an Array. This will contain your image name, so if your image is named “image1blah.jpg”, then your array will have to reflect that name, like this:

JavaScript
var image = new Array();
image[0] = "image";
image[1] = Math.abs(imagenumber);
image[2] = "blah.jpg";

The “currentimagevar will be the combination of this array, which will form the name of the image. The “image.src = currentimage;” will update the image source.

JavaScript
document.images['imagenumber'].src=image.src;

This line will display the new image.

And that is it! You got your image browser!

This type of image browser is nice for comic pages/strips display. Just remember that this browser needs numbers in the name of your image, because it uses those numbers to browse through the gallery. If your images are named “forestimage.jpg” and “beachimage.jpg”, this browser will not be able to browse through them, only the initial image will be displayed and nothing else. There might be a better way of doing this? Probably, yes. Should you look for it? You definitely should!

In programming, there are no completely right answers or right methods, there are only good practices and personal preferences. This is the way that I ended up creating myself starting from multiple other ways of doing this. Before coming up with this solution, I created like 10 more, and with each “update”, the code got smaller, cleaner and better. The last update I did to it reduced the number of lines by 50% and reduced time and effort required to add new images greatly. Does this mean there is no way of improving this? Well, if there isn’t, I would feel real sad now. But as I know that there must be, it’s okay. This is simply something for you to get started with, to get your brains itching for something more. And THAT is what this is all about!

All the best!

History

  • 18th November, 2009: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralNice intro, without buts Pin
Raul Mainardi Neto20-Apr-10 5:41
Raul Mainardi Neto20-Apr-10 5:41 
GeneralGreat prospect, but... Pin
Earl Brill7-Jan-10 15:31
Earl Brill7-Jan-10 15:31 
GeneralRe: Great prospect, but... Pin
AkumaNoRitomi14-Jan-10 17:23
AkumaNoRitomi14-Jan-10 17:23 
QuestionHow to test Pin
cwp4224-Nov-09 3:32
cwp4224-Nov-09 3:32 
AnswerRe: How to test Pin
AkumaNoRitomi24-Nov-09 19:04
AkumaNoRitomi24-Nov-09 19:04 
GeneralGood article, but a few things Pin
Helbrax20-Nov-09 9:05
Helbrax20-Nov-09 9:05 
GeneralRe: Good article, but a few things [modified] Pin
AkumaNoRitomi21-Nov-09 5:43
AkumaNoRitomi21-Nov-09 5:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.