Featuring the (very) charming illustrations with the site's mascot...
If you are a photographer or a writer sharing your art on the web, you may
sometimes wonder what could be the best pictures or quotes to display on your welcoming
page... If you've got a lot of content and only show the most recent one, people may
never see your older releases. And if you do a selection by yourself, you're never
sure to pick to ones people would like the most.
The solution? Try randomness!
Spare yourself the hassle of updating by hand your samples every day, and let chance
decide! If you already have a good amount of content, that will be the best way to keep
your visitors engaged and willing to see all you have to offer. That's what I am doing
of my websites, and it works pretty well!
There's many ways to do this, but all the pages you can find on the Internet regarding
this topic are either very incomplete, or lack crucial informations to make it work
flawlessly. This page aims to clarify things and make it simple, even for beginners!
Why use JavaScript?
Adding JavaScript (JS) to your page need nothing more than the script! No server
module, no browser extension. JS have been out there for almost 30 years and
is supported litteraly everywhere. Script interpretation happens at visitors' browser
level, meaning that even if your hosting plan billing is based upon bandwidth,
hits number or CPU time, you can add JS to your pages at no extra cost.
As you may have figured, my website uses a very old-fashined design and page layout,
with only plain HTML, almost no CSS and no on-fly generated content using PHP or
similar tools. Thus, I can keep my server configuration clean and very simple
(and stupid).
That doesn't mean I cannot do some funny tricks, just as in my
Manga Pink Zone where the sample images displayed
for each resolution are randomly picked upon page load.
That isn't restricted to images. Actually you can use JS to display random texts,
links or whole blocks of HTML content with almost the same code.
JavaScript & HTML integration basics
[ You may skip this part if you're already confortable with that - or head straight to scripts download if you're in a hurry! ]
The general structure of an HTML document including small JavaScript code looks like this:
<html>
<head>
<scripttype="text/javascript">
... script code goes here ...
</script>
</head>
<body>
... static HTML ...
<scripttype="text/javascript">
... another script code ...
</script>
... static HTML, continued ...
</body>
</html>
Yes, one may add JS almost everywhere they want. Generally, functions are
defined in the <head>...</head>
section, and function calls go in HTML body. But that's not an absolute rule - although
it would make no sense to write something with a script in the HTML header.
Another way to proceed is to create a separate file, as explained later in the
scripting alternatives section of this page.
Let's say we define a JS function Random_Content(content_type) in our header,
then we can then call it in our HTML body by adding the following to it:
And that's all! However, a good pratice is to allow something to be displayed just
in case JavaScript is disabled or unavailable. That could be of a use with crawlers,
that won't execute JS in most of the cases. Thus, displaying a "default content"
for non-human visitors would be interesting in order to keep pages well indexed
on search engines.
This is done by using the <noscript>...</noscript> HTML tag.
Anything delimited by it will be ignored by browsers executing JS code.
To sum up, our HTML body should look like this:
<body>
... main HTML body ...
<noscript>
Enable JavaScript in your browser to see my amazing random content!
</noscript>
<scripttype="text/javascript">
Random_Content("text");
</script>
... main HTML body, continued ...
</body>
It doesn't matter if we add our <noscript>
declaration before or after calling the script in your HTML document. One may add
whatever they want there, that could be their whole static page, meaning their entire
content will be generated by the script when executed.
Now it's time for some randomness!
Let's start slowly by creating a script that print a random pre-defined text line.
First we define the function:
text_to_display[0] = "This <a href=\"/en-index.html\">website</a> is incredible! Isn't it?";
text_to_display[1] = "Site's mascot is holding amazing assets... <a href=\"/mascot/\">Click here</a> to see more of her!";
text_to_display[2] = "Any question about the site? Read the <a href=\"/en-faq.html\">FAQ</a>!";
text_to_display[3] = "I need to add more random quotes here... Come back soon!";
n = Math.floor(Math.random() * total_messages + 1);
document.write("<b>Random Quote #" + n + "</b>: " + text_to_display[n-1]);
}
</script>
This one goes in our <head>...</head> section.
It defines an array of three quotes ready to be printed, written just as if they were
to be statically included in any HTML document. Thus, it may contains
links or any HTML tag. As each definition must be enclosed into
double-quotes ", we need to use '\' as an escape
character to actually print a double-quote.
The next step is to pick a random integer (1, 2, 3 or 4) and then make the browser
show the quote, when it will execute the final
document.write line.
There's a little trick: arrays of
n elements get numbered from 0 to n − 1, but we want
to avoid displaying "Quote #0" which would feel a bit odd.
By changing the value of total_messages, and then
populating the text_to_display array accordingly,
we may add as much quotes as we want.
Now we can call that function somewhere in our page by adding in our
.html file:
<center>
<noscript>
<fontsize="+2"><i>JavaScript disabled! You cannot see this example in action...</i></font>
</noscript>
<scripttype="text/javascript">
Random_Quote();
</script>
</center>
And here is the result - hit your reload button!
Yes, it's as simple as that.
That was a good appetizer, wasn't it? Now we go for the main course, random images!
The first thing to do is to organize images & thumbnails repository. The best
is to use numbered image files: image-1.png, image-2.png, ...
It's always better to prefer a plain numbering plan instead of a "fixed length"
naming scheme, meaning image-42.png is to be preferred over
image-0042.png.
If using such a file naming scheme isn't possible, there's a solution when the
webserver is running on UNIX: create symbolic links.
And so on. If that's also not possible, there's an
alternative but it's less
convenient. From now on, let's suppose our image archive uses numbered filenames.
I've got several images (16 in total) of my site's mascot featuring her in a scene
with computers and green matrix-like fictionnal texts, such as the one illustrating
this page. They are all named nuna-matrix-1.png,
nuna-matrix-2.png etc. Thumbnails are named
nuna-matrix-1-m.jpg, nuna-matrix-2-m.jpg, ...
Inserting one of these thumbnails within a webpage with the associated link to the
full-sized image would look like this:
Now let's write a script that prints repeatedly similar HTML lines,
but with different image & thumbnail numbers each time, randomly chosen.
On top of that, we ensure each thumbnail displayed will be unique!
Here is the script. Explanations will follow just after.
// The grand finale document.write("<br><i>Click a thumbnail to open the full-sized image!</i>");
}
</script>
The main idea is to break the HTML code to print into several elements that
won't change from one line to one another, and then reassemble each of these parts
with the image number.
Step 1 consists in building the index containing the
randomly-picked image numbers, judiciously named
images_index. We start with an empty array.
Then in a loop, we pick a random integer ranging between 1 and the value of
total_images (both included) and then check
in a sub-loop if we already have this number in
images_index. If no, we push that number
into the array - if yes, we pick another number. We do this
until the array is filled with display_images
numbers, the amount of images to display.
Step 2 is the main loop: we build each HTML statement, then print it
to our page. Each time we are done with as many as the
joined_images parameter, we insert a break
<br>, otherwise we just print a
non-breakable space. Should we prefer our thumbnails to be sticked to one another,
we would drop this .
Eventually after this main loop, we finish by printing a little helper text,
telling the reader thumbnails are clickable and give access to the full-sized image.
Again, hit your reload button! But try not to fall in love with the mascot...
Feel free to experiment with different layouts by changing
display_images and
joined_images when calling the script!
You also have the possibility to adjust
total_images, e.g. if you're not willing
to give access to all of your images for free. And if you don't want to add any
break at all, and get all the thumbnails on a single line - for instance,
if you plan to embed that in a slider with its own scrollbar - then just use a
joined_images parameter greater than
display_images.
However, keep in mind that those are not
so unbreakable, and if there's too much images on a single line, they may be split in a
very messy way on those mobile devices... One can circumvene this by adding a
.no-wrap{white-space: nowrap; }
to a .css file or in their header's
<style>...</style> declaration, and then enclose the thumbnail groups that shouldn't get splitted into
a <spanclass="no-wrap">...</span> HTML block.
Scripting alternatives
Let's now explore some possible improvements, or other ways to proceed
one might need to make things work as they expect!
To keep HTML documents clean, it's better to define needed JS functions in a
separate file. That's actually what I am doing on my whole website. Let's suppose
we want to use such a file, and let's call it my-functions.js for instance.
Into this file, raw JavaScript code should be inserted without any header or tag. Then
it should be included in the .html file within its header like this:
<html>
<head>
... HTML header declarations ...
<scriptsrc="my-functions.js">/script>
... HTML header, continued ...
</head>
</script>
<body>
... static HTML ...
<scripttype="text/javascript">
// Calling a function from my-functions.js Function_1(parameter_1);
</script>
... static HTML, continued ...
</body>
</html>
As many .js files as needed can be used, they just have to
be all declared in-a-row:
In case these files aren't located in the same directory as the .html file,
relative or absolute paths can be specified.
We've seen earlier that a numbered file naming scheme
is of a great help to be able to write a conciese JS function. Although, if files
cannot be renamed or if the symbolic link trick cannot be used either, there's a
workaround: define arrays of the appropriate size inside the function, and fill
them with the filenames:
Note that we got rid of the total_images as a
calling argument of the function and instead specified it as a variable, as the size of
the statically-defined arrays inside that function must match the number of images
in the repository.
Then, the document.write
line in the main loop will look like this:
The whole script is somehow a merge of the code we used earlier for random quotes,
with the one that displays random images.
On top of displaying random pictures, we can optionnaly get them sorted.
Depending on how your repository is organized, it may ensure similar
images will always appear next to one another. This can be done with just a few
changes to our function. First we define a new variable named
init_index that will be the one to get populated
with random numbers. After this, we sort those numbers and transfer all of them in the
final array
images_index we use to print the HTML lines.
The latter can be achieved with just one extra line of code:
varimages_index = init_index.sort(function (a, b) {returna - b; });
// The grand finale document.write("<br><i>Click a thumbnail to open the full-sized image!</i>");
}
You may copy this script directly from this page, or
download it along with all others seen before.
Let's call it with Random_Sorted_Images(16,6,3)!
If you are viewing this page on a desktop browser, you'll notice by overing the
thumbnails that image number is growing on each line, from left to right.
Download the scripts shown on this page
I have prepared a little zipfile for those who want to try it at home!
They're almost ready to use - the only thing you'll need to change is the
quotes or the path to your images in the main document.write line inside
the code.
TheRaphit's Web Site - The last homepage on the Web
This is my personal website, which I opened in 1997. Since then, I've been
fighting censorship and political correctness to provide you with content that
"some people" don't want to see available for free on the Internet...
Here, I'm trying to revieve the good'ol'times, when the Web
was fresh and really entertaining!
Want to know more about what the f*** is that site?? Read my
illustrated FAQ!