Making an online gallery of pictures should be a quick process. The gap between snapping some pictures and publishing them on the web ought to be a short one. Here’s a quick and easy way of making a one-page gallery that uses JavaScript to load images and their captions on the fly.
The mark-up#section2
I’ve put together some photographs that I want to make into an online gallery. The simplest way of linking to the images is to put them in a list like this:
<ul>
<li><a href="images/bananas.jpg" title="A bunch of bananas on a table">some bananas</a></li>
<li><a href="images/condiments.jpg" title="Condiments in a Chinese restaurant">two bottles</a></li>
<li><a href="images/shells.jpg" title="Seashells on a table">some shells</a></li>
</ul>
Right now, clicking on one of those links leads straight to the image. I’m going to use JavaScript to intercept that click and perform a different action instead.
The JavaScript will dynamically update a placeholder image and description, creating a slideshow effect.
I’m going to use a blank .gif for the placeholder image. I could just as easily use the first image in my gallery or some kind of “intro” image. The important thing is that the image and the description have unique IDs. I’m going to call the descriptive paragraph desc
and the image placeholder
.
<p id="desc">Choose an image to begin</p>
<img id="placeholder" src="images/blank.gif" alt="" />
Don’t add any height
or width
attributes to the placeholder image or else all the images in the gallery will be squeezed or stretched to the same size.
The JavaScript function#section3
Now it’s time to write the JavaScript. This should be placed in the <head>
of the document or in an external file. I’ll call the function showPic
function showPic (whichpic)
As you can see, this function will be accepting just one parameter: whichpic
. This refers to the link pointing to whichever picture I want to display.
The showPic
function is going to be interacting with the desc
and placeholder
elements by referring directly to their IDs. The first thing I need to do is ensure that this is a capability of the browser executing the function. This is done by checking for the existence of document.getElementById
:
if (document.getElementById)
Once the browser passes that test, the placeholder image can be swapped out. This is done by replacing the src
value of the placeholder with the href
value of the whichpic
link:
document.getElementById(‘placeholder’).src = whichpic.href;
At the same time, I want to swap out the text within the desc
paragraph. I could use proprietary JavaScript such as innerHTML
but there’s a cross-browser solution available in the form of childNodes[0].nodeValue
. This expression means the value of the first child node of an element. In our case, that will be the text inside the element.
The desc
text can be replaced with the text from the whichpic
link:
document.getElementById(‘desc’)» .childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
But it would be even better to replace the desc
text with the content of the title
attribute from the whichpic
link:
document.getElementById(‘desc’)» .childNodes[0].nodeValue = whichpic.title;
I needn’t decide on one arbitrarily. I can test for the existence of a title
attribute. If it exists, use that text. Otherwise, use the link text:
if (whichpic.title) {
document.getElementById('desc')» .childNodes[0].nodeValue = whichpic.title;
} else {
document.getElementById('desc')» .childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
}
Lastly, I want to make sure that the whichpic
link isn’t actually followed by returning false
:
return false;
Unless, that is, the browser didn’t understand document.getElementById
. In that case, I do want the link to be followed so true
is returned instead.
Here’s the finished function:
<script type="text/javascript" language="javascript">
function showPic (whichpic) {
if (document.getElementById) {
document.getElementById('placeholder')» .src = whichpic.href;
if (whichpic.title) {
document.getElementById('desc')» .childNodes[0].nodeValue = whichpic.title;
} else {
document.getElementById('desc')» .childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
}
return false;
} else {
return true;
}
}
</script>
Calling the function#section4
All that remains is to call this function from each of the links. In order to pass a value for whichpic
, each of the links could be assigned a unique ID. However, it’s much easier just to pass the value this
which would mean that whichpic
will have the value of “this element calling the function.”
I’ll use the onclick
event handler (it would be a good idea to also use onkeypress
for people navigating by keyboard). Because the showPic
function determines whether the link is actually followed or not, I want the action of clicking the link to return whatever the function returns. If the function returns false
, the link isn’t followed. This done by using onclick="return showPic(this)"
.
<ul>
<li><a showPic(this)" href="images/bananas.jpg" title="A bunch of bananas on a table">some bananas</a></li>
<li><a showPic(this)" href="images/condiments.jpg" title="Condiments in a Chinese restaurant">two bottles</a></li>
<li><a showPic(this)" href="images/shells.jpg" title="Seashells on a table">some shells</a></li>
</ul>
Let’s see it in action.
function showPic (whichpic) {
if (document.getElementById) {
document.getElementById('placeholder').src = whichpic.href;
if (whichpic.title) {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
} else {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
}
return false;
} else {
return true;
}
}
There you have it: a simple JavaScript image gallery. It degrades gracefully so that older browsers can still follow the links and see the images. It works as expected on IE5+ and Netscape 6+ on Windows and Mac. It also works in Safari and all the various flavors of Mozilla like Firebird and Camino.
Thanks for sharing, Jeremy. A simple and smooth technique, useful for quickposting pictures.
One thing though. Honestly, I’d expect an “image gallery” to have… thumbnails.
Surely it would be easier to just include an “image gallery” JavaScript link in the header and that’s it? Add a line like “” to the header, and then put this in jsimggal.js:
function showimg(e) {
if (window.event)
l = window.event.srcElement;
else
l = e.target;
document.getElementById(‘desc’).firstChild.nodeValue =
l.getAttribute(‘title’);
document.getElementById(‘placeholder’).src = l.href;
if (window.event) {
window.event.cancelBubble = true;
} else {
e.stopPropagation();
}
return false;
}
function make_img_gal() {
if (!document.getElementById || !document.getElementsByTagName)
return;
var lnks = document.getElementsByTagName(‘a’);
for (var i=0;i
Hi Jeremy,
Goed clear article, especially with the degrading trick.
I’ve done somewhat the same, but I’ve stumbled upon a not-so-good-looking asset of this method. What if you’ve got a it larger picture, but with different dimensions then it’s predecessor. At some point the image would have to be resized, and preferable when the image is totally loaded, so no images are distorted.
Have you looked into checking when an image is totally loaded?
Maybe this is too farfetched for an album with smaller images that load fast and all have the same dimensions.
My method is MSIE5+ only unfortunately, but if you use this browser you can check out what I mean at:
http://www.trustphotosite.com/robert/TackFoerMaten/ (wait for the thumbnails to be loaded before you can see the effect in action)
Thank you for you explanation anyway.
Robert
PPK told ALA to stop publishing JS articles. I disagree. I think they should stop publishing articles all together.
Manuel, I agree that thumbnails would be nice. There’s nothing to stop you using thumbnail images instead of text in the links though. The script relies on the “href” and “title” attributes to work – what goes between the opening and closing tags shouldn’t make any difference.
Sil, you’re quite right: using an external file combined with event capturing would be the most unobtrusive way to get the same effect. Unfortunately, a side-effect would be that it would act on *every* linked image on the page, not just the ones in the list.
Robert, you’re right about the varying sizes of the images. This script works best with images that are roughly within the same range of sizes. If the images vary wildly in size, there can be unintended layout consequences.
Without knowing much about Javascript, would it be possible to use Sil’s code with a modifier that specifies all links within a named div?
I do appreciate the contingency design in the ALA code tho. It’s a great solution with thoughtful attention to structure, well done.
1. Add this:
if (document.all) {
document.getElementById = document.all;
}
and the thing will work in IE4 too.
2. It is possible to find out where is the link on click event. Using obj.parentElement / obj.parentNode
Or you can check the href (whetet contains the gallery string and it is .gif or .jpg)
or ‘Another Pointless Artical’
So kiddy script DOM tricks are the new black?
I have been writing code like this and that described in http://www.alistapart.com/articles/footers for three years and consistent browser support is still bad for DOM and now I’m bored of it.
Articals like this make me think that we have come back to cross browser hacks to make things work. Have we really moved on from NS4 ? Seems not.
How about an artical in writing a ticker tape message scoll within a browser status bar – that would be really cool.
While it (apparently) may not be as full of a solution as some people would like, and (apparently) doesn’t do every feature that others would like, real life examples of simple JavaScript use like this are exactly what I need to pick up a bit of coding skills (and, probably, investigate further when I need to tweak it a bit).
There are probably quite a few (similar, but quieter folk) out there like me that just got inspired to dig a bit deeper into the scripting world.
>I have been writing code like this and that described in http://www.alistapart.com/articles/footers for three years and consistent browser support is still bad for DOM and now I’m bored of it.
May we see the articles you’ve written?
This is great article but I was just wondering if it is possible to target another page that contains the placeholder image. There are times for one reason or another I want the image to appear on a separate page, but do not want to create a page for every image (and also want something nicer than just viewing the image on the server). I am not experienced with Javascript so I may be asking for something that is not possible. Thanks for the great articles ALA.
As someone who isn’t particularly interested in being a javascript expert (or snob, as some people seem to be), I appreciate when others provide quick and useful solutions to my design needs. I know I’ll be using this script and am grateful for the time I’ve saved not having to dig through thousands of scripts that may or may not work or ones I need to modify with my limited knowledge. Besides getting a handy script, I also learned a little bit about javascript so thanks for the gift!
You’re welcome, Lauri. I hope the script will come in useful.
Johnboat, I believe it’s entirely possible to have the placeholder image in another page as long as that page has a name that we can refer to. So if it’s a window that has been popped up using JavaScript, the important thing is to use a variable when you create the window.
Let’s say you popped up your new window like this:
window.open(‘picturebox.html’,’mywin’, ‘toolbar=no, scrollbars=no, resizable=no, menubar=no, status=no, directories=no, location=no, width=360, height=280’);
What you need to do is use a variable. Let’s call it “mynewwindow”:
mynewindow = window.open(‘picturebox.html’,’mywin’, ‘toolbar=no, scrollbars=no, resizable=no, menubar=no, status=no, directories=no, location=no, width=360, height=280’);
Now all we need to do is adjust our original script slightly.
Where it used to say:
document.getElementById(‘placeholder’).src = whichpic.href;
…we could now say:
mynewwindow.document.getElementById(‘placeholder’).src = whichpic.href;
and where it used to say:
document.getElementById(‘desc’).childNodes[0].nodeValue = whichpic.title;
…now we say:
mynewwindow.document.getElementById(‘desc’).childNodes[0].nodeValue = whichpic.title;
Hope that helps.
Thanks for the great article & the help. I will give your suggestion a try. Take care.
Hey kids! Tired of incompatible DOMs? I saw a post earlier that used a make-shift prototype for IE4:
document.getElementById = document.all
That’s incorrect. I can help.
Here’s my DOM API that you can use:
//Powered by DCScript
function DOMCall(name) {
if (document.layers)
return document.layers[name];
else if (document.all)
return document.all[name];
else if (document.getElementById)
return document.getElementById(name);
}
Call it like so:
DOMCall(“object”).style.color=”blue”;
Where “object” is the object’s id.
Feel free to use it.
–Dante-Cubed
While the deprecation into older browsers is a very nice aspect of this piece, it seems to still lack something, being just a bit too basic. Also, after you build up more than a few items, the list as a way to navigate the photos is simply not going to work.
I would suggest packaging up this technique, and using the techniques from CSS Sliding Doors, retool the list into a more slideshow or photoblog presentation. Then add the “Next” and “Prev” style actions and THEN you’d have a juicy article around making a standards compliant photo browser that also deprecates into media that can’t deal with the style sheets.
Just my two cents.
This javascript slideshow doesn’t work properly in IE 5.5:
(1)On link click get error message null or void.
(2)When the image displays, the links disappear!
This is probably a dumb question but in regards to the variable “mynewwindow” from Jeremy’s “Targeting another window” post, where do I place it? I assumed (and this is probably my mistake) I would place it at the begining of the javascript. I also assumed the function would still be called in the same manner as the article describes. I tried this to no avail.
As I mentioned in an earlier post, I am not familar with javascript so I apologize for what is probably an elementary question. Thanks again for the article.
Here’s what I came up with when I wanted to make a photo album with replacable big picture at http://www.hot.ee/citikas/album-cats.html
It is my first dabbling in JS and probably is not the best solution. Should I replace it with the ALA script?
Great Article!
Really nice website and even comments are great and helpful !
nicely written, but where php would be a better choice (for galleries for example) i would not use js (actually i quit using it all together i have enough cross browser hacks for my css alone!). But, nice site (adacio)Jeremy and good article.
To all the haters out there (read: Dante-Cubed and APA), please lighten up. This may not be the most complex/extendable script ever written, but it will be very useful to a large portion of ALA’s readership. Remember that these articles are written “For people who make websites,” not just advanced JavaScript programmers who make websites. If you can’t learn anything from this particular article, bite your tongue and move on to a different site. There is plenty of great stuff on O’Reilly Net and SitePoint.
Nice article Jeremy. Cheers.
That’s right Dante-Cubed and APA…
Here is a simple solution to help you get over that I’m-mad-at-the-world-and-I’m-going-to-take-it-out-on-(insert forum name here).
If you don’t like it, don’t read it. Resist the urge to type in that URL. Delete your bookmark. Take a deep breath. It’s not worth it. No one’s going to read past that first flame-esque initial angry line you wrote.
Vaire, your script works well. They only difference between yours and mine is the matter of backwards compatibility.
By having the “onlcick” event handler within hyperlink (rather than on the image) and having JavaScript cancel the act of following the link, the list will work for people without JavaScript. So you might want to adjust your script rather than replace it entirely.
On the other hand, your script shows how this idea can be applied to thumbnails, not just text links. This is pretty much exactly what Manuel was talking about here:
http://www.alistapart.com/discuss/imagegallery/1/#c6528
William, I can’t seem to reproduce the error you’re having with IE5.5. Is anybody else seeing the problem described here?
http://www.alistapart.com/discuss/imagegallery/2/#c6576
s26, I agree that a server-side solution is nearly always the way to go for things like this but, as is made clear at the start of the article, this intended as a kind of “5 minute meal” for when you’ve got some pictures you’ve just got to get online quickly.
This would probably involve considerable work, but what would relally make this script even better would be the addition of simple last picture/next picture buttons. Unfortunately, this would probably involve feeding all of these URLs into an array. Anyone know any easier way to do it without modifying the code as much?
While I agree that usually a server-side script might be better for something like this, it can help a lot to use JS if you are with one of those cheap hosting companies that will suspend your account if you exceed some unspecified level of resource use. In a case like that, the more you can put off onto the client the better.
BTW, I love this site, ever since I ran across it about six months ago when I decided to bit the bullet and start working with CSS. A link from http://www.glish.com led me here. Google led me to glish. I printed out several articles that I use for my evening bedtime reading. Great stuff!
Normally I’m very polite and reserved when it comes to differing opinions but recently the posts we’ve had on ALA discussions have got me pi**ed off.
In a nutshell: STOP MOANING IF YOU DON’T LIKE AN ARTICLE!!
Everybody who frequents this site are at different levels of expertise in our profession so it’s bloody obvious that an article is going to have different merit to different people. If it wasn’t useful to you, then fine but I’m sure it was to other people. STOP BITCHING!!
So OK, a JS-driven Image Gallery isn’t exactly cutting-edge web content, but the concepts and approach used is a good demonstration of crisp, clean DOM scripting and *THAT* is where I found the article to be useful.
So instead of moaning “oh, this article is shit because the title says ‘image gallery'” try to realise that it’s the *techniques* that some people find useful, not the end result.
Oh and if you really think ALA is going down hill because of “kiddie JS articles” or “CSS hack worship” then why not politely contact ALA with article suggestions (you never know, they may write one or know of somebody who can provide) or not heaven-forbid put your money where your mouth is and write an article of your own.
johnboat: I wanted to do something very similar to what you’re describing a couple of years ago. While my solution is not really the most elegant, it does work:
http://www.hooloovoo.net/cats/
Feel free to re-use the code, (but not the images/content mkay?) The js file can be found here:
http://www.hooloovoo.net/js/catwindow.js
sorry it’s not well commented.
Basically I used JS to write the html code to display the page on the fly as opposed to using a placeholder image.
This works perfectly in Moz, but when I open it in IE6 things don’t go well (surprise). When I click on the image link in IE:
The image is not displayed on the same page. It goes directly to the image.gif file and displays only that image on a new page.
I love CSS, but I’m admittedly a JavaScript novice (flame away). Any thoughts?
It’s no reason to start spamming up my website, like some of you have. My website is on a completely different topic, such nonsense belongs on a lesser website (this is perfect).
Add to the list of names I’ve been called: hater.
Shakey you closed a rant tag that was never opened. Well, the W3C will probably hang you for such bad XHTML. That’s the price you pay for following standards.
I wrote a story about this topic at http://www.geocities.com/seanmhall2003/SeanSoft/eir.html (EIR is copyrighted). There you can see that we all run into JS problems, but it’s sites like these that are turning web developers away from practical JS (although this article was OK). So there’s a method to my madness. And the ends justify the means.
Hey Jeremy,
Great article and a nice simple javascript it is. I like the fact that it works consistently with the majority of popular browsers out there. Thanks for sharing this with us.
Pathetic, Dante-Cubed, just pathetic. What possible benefit did that comment offer? But I’m dropping this now as comments such as a flame war on ALA will get me slapped…
Regardless of the likes of these people, I would urge those less advanced in their web disciplines to read on and enjoy whatever is useful to you – I for one will be implementing this JS technique on a number of my projects.
This is great. I’ve been searching for a script like this so I can create a “portfolio” section on my business site. I am a webdesigner and not a javascript coder – so this is perfect. This will help me display my client projects all on one page.
Thanks guys – keep it up.
I’m sorry but.. how can I close the img?
One approach would be to add another link saying “close” or whatever and you just swap in the oringinal blank image placeholder. Also have your alt tag empty too to empty the caption text.
It’s called sarcasm.
Instead of “Flame War” I prefer “Battle for DC’s Rights”. Some civil comments of mine were deleted because I said I didn’t like the article. This is what set me off.
I used a simpler version of this script recently for this image gallery:
http://adactio.com/extras/okkervilriver/
This time I’m using thumbnails and there’s no descriptive text to be swapped out. Effectively, it’s a contact sheet – a way of choosing the best pictures out of a collection.
(The backstory to this gallery is that I was contacted by the singer of the band Okkervil River who liked a picture he had seen on my site of his band and asked if he could re-use it. I told him I had taken lots of other pictures and promised to quickly throw them online so that he could choose which ones he wanted.)
I had all the original pictures in iPhoto. I used the “export” option and chose “web page” as the output format. I then kept the thumnails and resized images that were exported and promptly thrashed the HTML that iPhoto had generated.
This got me thinking… iPhoto is Applescriptable. I know there are a couple of alternative “export to HTML” scripts out there already. Maybe somebody could mix iPhoto, Applescript and the image swapping script from this article to come up with a “contact sheet” style export script?
Just a thought…
It’s better to use a loop inside an onload handler than to clog up your markup with the onclick attribute.
Just saw this article, and loved the js powered image library idea. I set up a little gallery as a test, and would have to say tha I’m quite impressed.
Expanding on the idea I added in some css and dhtml styling, and came up with a quick and easy to use multi-page image gallery.
Unfortunatly due to the IE whitespace bug I had to stick all the thumbnails on 1 line to prevent the floated thumbnails from doing wierd things. I’ve tested this out in IE/mozilla for windows and Safari for mac and things seem to work great. The styles are never seen by NS4 so they get the content without all the design.
I think i’ll take this idea a little further even and write a small application to auto generate the html files for me.
Thanks again!
Feel free to check what i’ve done at: http://dasme.org/imagegal/
I just got a job to do a photographers site, good timing ALA.
To: APA,
I bow before you. :/
Dasme, your image gallery looks great!
Using DHTML to show and hide the different pages is a stroke of genius. You’ve managed to pack a heck of a lot of information into one page and yet because the user chooses which portions they want to view, it isn’t at all overwhelming.
JavaScript + CSS + good information architecture = very cool indeed.
The idea of an application to create the pages automatically sounds really exciting.
I realize this may sound idiotic to some of you advanced folks out there, but I’m a novice scripter so this is baffling me:
I wanted to see if I can replicate this script’s effect as-is. Here is the current page with all the photos: http://www.villagepreschoolcenter.com/photoalbum.html
Instead of all those images. You can see why I’d like to use this technique on that page. Anyway, I wrote the script as described, altered the markup, but for some reason it doesn’t work and I can’t figure out why. A live test is available, though not public, at http://www.villagepreschoolcenter.com/gallery.html
View source to see what I did, and maybe you can set me off in the right direction again. Advance thanks and brownie points to all those who offer help.
Oh, and…can anyone offer some resources or documentation of what these “nodes” are? I didn’t understand that much…
Thanks again!
http://www.quirksmode.org/dom/intro.html
I’d expect anyone with no computer knowledge at all to know what a node is.
Dude, Dante. Honestly. You have a geocities.com page.
I mean, let’s just think about this: geocities.
I posted my very first pit-cher on a geocities homepage and stuff.
You’re crackin’ me up, man.
Okay, I appreciate the resource Danté. 🙂 (No, seriously I do. I’ll just pretend that was the whole post.)
Anyway, I did a bunch of trial-and-error runs on this Image Gallery script and noticed the following:
it all works fine — UNTIL I nest the the second if statement to test for a title attribute. For some reason, using nodes and/or testing for this title attribute sends my javascript awry. And by awry I mean: will always return TRUE and jump me off to follow the link. I can’t seem to reference the desc paragraph.
Here is the page with a bunch of alerts _intended_ to show where the execution of the script is: http://www.villagepreschoolcenter.com/gallerytest.html
By the way, if this is an inappropriate forum for this particular kind of discussion, I’d appreciate it if someone just let me know where I _should_ be asking about this.
Thanks again!
1. You can use my DOM API I posted here earlier to solve document.getElementById and other DOM problems.
2. Instead of childNodes[0].nodeValue, use .innerText or .innerHTML. It’s easier and faster.
3. Main problem: you have an else statement INSIDE and IF statement. Fix that.
—
4. I have a geocities page. Yeah. We’re not all rich. I can’t really afford my own server. I’m saving up for a guitar amp. I AM only 14.
Dante,
thank you again for your advice. I’m familiar with innerHTML and innerText, and thanks to your resource at quirksmode.org, now I know what nodes are.
However, I don’t understand what you mean by my main problem being an else statement inside an if statement.
I tried to use _the exact same JavaScript,_ character-by-character, that was written in this article (which, DOES work in the same browser I’m trying to use), and this script in this article has an else statement inside an if statement.
Why is this a problem on my pages but not here on ALA’s article?
I’ll keep tinkering. :
Thanks again to anyone who can help.
What I meant was you forget to end one if statement with a }. That “}” was missing. You can’t have an if inside one. You had something like this:
if (document.getElementById)
{
document.getElementById(‘placeholder’).src = thepic.href;
if (thepic.title)
{
document.getElementById(‘desc’).childNodes[0].nodeValue = thepic.title;
alert(‘This executed the: IF->IF STATEMENT’);
}
else…
There should be a “}” right after before the else. I make the same mistake. Make sure you have your “}” in the right places and the correct number of them as well.
There should be two end braces before “else”
Thanks for your advice, and your patience.
I took another look at the script on http://www.villagepreschoolcenter.com/gallerytest.html but I was unable to find a problem; that is, all the braces (“}”) are in the right place. Take a look at the page and view the script for yourself. You’ll notice that the alerts function just fine, and that the nested if statement (as well as the nested else statement) execute properly. In this page, I’ve commented out the offending lines so that the only thing running is the swapping of the picture and the alerts to track the script.
Now, if you’ll go to http://www.villagepreschoolcenter.com/gallerytest1.html you’ll find the _same exact script_ with the exception that the lines
document.getElementById(‘desc’).childNodes[0].nodeValue = thepic.title;
and
document.getElementById(‘desc’).childNodes[0].nodeValue = thepic.childNodes[0].nodeValue;
are uncommented. Since the alerts show me where the script is executing I’ve narrowed the problem down to these two lines. In each case, the script runs just fine _until_ we get to one of these lines, when, for some reason, the browser ends up following the link and loading the improperly.
What could be rwrong with these lines? 🙁 I’m just stumped.
Anyway. Thanks, yet again.
Your code is way too complicated. Instead of childNodes[0], use firstChild. It’s the same thing. I don’t know what’s wrong. I haven’t the time to help newbies. I’m writing my own version which is simpler than this.
I told you what was wrong. If you have nested if statements you else if. That’s what’s wrong.
If you just used my DOM API you wouldn’t need the first if.
Here it is again…
//Powered by DCScript
function DOMCall(name) {
if (document.layers)
return document.layers[name];
else if (document.all)
return document.all[name];
else if (document.getElementById)
return document.getElementById(name);
}
Call it like so:
DOMCall(“object”).style.color=”blue”;
Where “object” is the object’s id.
I tried to put my money where my mouth is by writing an article about combining IE’s and the W3C’s DOMs. It produced quite useful effetcs, but here is what happened:
ALA Editor: it works in IE? NOOOOOOOOOO!!!!!!!!!!
So I assume that if it worked, it was too good.
Heh.
Is there a way to modify this so that there is
A. a pop up window to see the pics in
and
B. a way to tell it to scroll thru a certain number of jpg’s or maybe a particular folder?
I am thinking that if I just plug in my digital camera, I get a buttload of jpg’s named DSC101, DSC102,DSC103,etc. I would like to not have to label them and reference that label in order to put them online using this javascript.
I thought the article was pretty useful and its simplicity prompted me to quickly create my own strange interpretation, which i’ve called The Germ Gallery at: http://ja.design.users.btopenworld.com/experiment/js_gallery/
“4. …I AM only 14.”
—-
Which is obvious to the casual observer.
Jeremy:
Useful article – bears directly on a current project – THANK YOU!
Allowing a script to browse through a folder is a security hazard.
Okay, I’m gonna give this one more (final) go. This seems to be working for everybody except me, so obviously something I’m doing is flawed. That said, I’m at a total and utter loss at trying to figure it out — I’m stumped.
I just looked over the Germ Gallery that Jon showed us. (By the way, it’s very nice. I like it, lots.) 🙂 Anyhow, I went through the js.js script you ran on that, Jon, and it is functionally identical to what I am using on this preschool’s gallery test page (at http://www.villagpreschoolgallery.com/gallerytest1.html ) and yet, the browser will always end up following the links.
What is different? What is wrong in my gallery that’s causing this? Anyway…I don’t mean to be a pest, (advance apologies if I am) I just really want to understand what is happening.
Thanks again.
I can’t get anywhere with that link. I told you what to do. Get rid of the first if statement and replace it with the DOM API (then, no problem with braces plus it becomes more usable). I can’t help you if you won’t listen to me.
Firstly, an onmouseover event should be added to the links making the status bar display something like ‘view (title)’ where title is dynamically extracted from the link’s title attribute. This will minimize confusion for visitors in a javascript-capable browser expecting a new page to load.
Secondly, non-javascript users should be pointed to a server side version of the same page. Those that commented that this should be done solely on the server side miss the idea that this solution saves bandwidth for both you and your visitors.
This photo gallery provided a quick solution for a simple business’ website. We’re finishing up a complete overhaul of our site and after fighting with complicated javascript (& dreamweaver) that this college student does not understand, this article was the light at the end of the tunnel! Now our “facilities” page will be as cool as the other guy’s 😉
I had a look at your preschool image gallery code and also ran into issues. You can check out the gallery that I did at http://dasme.org/imagegal/ and copy the script code that I use. On that page the second pic has a caption that will appear when clicked.
I am really not sure why your page breaks with the code that you have, but I can assure you that mne works. Try using my script and see if that helps. I origionally thought it may of been the doctype def that you are using on your page, but my page still properly renders and works with the base html 4.01 trans definition. I’m stumped 🙂
Well Dante, you’ve shown some aspect of maturity by at least trying to be helpful towards another poster. Who would have thought such compassion would be forthcoming from someone who otherwise gives the impression of being a spiteful troll?
It is unfortunate that you feel it necessary to jump and stick your oar in whenever knowledge is shared and sad that this web of ours allows you to do so with such unhelpful frequency. You rail against the ‘flashy script-hacking’ that goes on here. Well, I’m sorry to say it, but a lot of the sites that go on to be created by those who read and learn here are a damn sight more successful and with a far higher aesthetic value – ie: as an added bonus to looking nice, they WORK! – than your own site, which you are evidently quite proud of.
Could it be then, that this site of which you are so proud is the same one that brings up an alert if you dare visit with Mozilla berating you for your choice of browser and steadfastly refusing to work in the way it was obviously intended? I congratulate you on your narrow and counter-productive efforts.
Physician heal thyself.
PS. I’m sure PPK is thrilled by your evangelical use of his moniker as a means of shoring up your arguments instead of having actual originality of thought. Do you pay him the licensing fee?
An interesting bug in http://www.villagepreschoolcenter.com/gallerytest.html, which took me longer to track down than I planned!
Your script fails when you try to assign some text to
document.getElementById(‘desc’).childNodes[0].nodeValue
It’s failing because that node’s a leaf: it doesn’t have any child nodes. The quick’n’dirty fix would be to change ‘
‘ to ‘
some placeholder text
‘. Then it would have a text node as its first (and only) child.
As an alternative (or in addition) you could add a little sanity-checking and recovery to the script itself. I am
not a DOM scripting wizard. But something like the following should work.
function showPic( theAnchor ) {
// Assigns the value of theAnchor.href to document.getElementById( ‘placeholder’ ).src
// And sets the text of document.getElementById( ‘desc’ ) theAnchor’s title or to its text content
// Returns false on success, true on failure 😉
// Disclaimer: tested hardly at all and only in Safari1.2
if ( document.getElementById && theAnchor.tagName == “A” && theAnchor.href && ( theAnchor.title || ( theAnchor.firstChild ) ) ) {
myImageElement = document.getElementById( ‘placeholder’ )
if( myImageElement && (myImageElement.tagName == “IMG”) ) {
myCaptionElement = document.getElementById( ‘desc’ )
// We probably should sanity-check what kind of element we have here.
// But there are an awful lot of valid possibilities, so
// it’s an exercise left to the reader
myCaptionText = theAnchor.title ? theAnchor.title : theAnchor.firstChild.nodeValue
myImageHref = theAnchor.href
myImageElement.src = myImageHref
if ( myCaptionElement.firstChild ) {
myCaptionElement.firstChild.nodeValue = myCaptionText
} else {
if( document.createTextNode ) {
myCaptionElement.appendChild( document.createTextNode( myCaptionText ) )
} else {
// no caption set. But never mind….
}
}
// image loading should have been ok so
return false
}
}
//failed so
return true
}
I don’t know thy this is so complex.
if (!document.getElementById)
var r = false;
else var r = true;
At the end:
return r;
Why use all that complex if/else code when the above (or adding the DOM API) would’ve done?
I use a browser detect (very bad desicion, but I needed to). Mozilla and all none-IE browsers totally screw up everything, so I disabled it. It will be fixed in the redesign (if I do it), but for now I punish these browsers. Yes. What a bad designer I am. Can we change the subject?
I recently agreed to make a web page for my wife. I hade coded a little html in the mid-90’s when things were much simpler (and boring by today’s standards). I figured I’d better come up to speed before starting. Wouldn’t you know, of all the web design books at Border’s, I picked Zeldman’s DWWS. Lucky me.
Imagine my frustration in trying show a LOT of images (my wife Rebecca is a lampwork glass bead artist) AND use css AND make it compliant AND make it smooth. Dang.
Anyway, I came up with something that is akin to Mr. Keith’s idea but different. Take the code if you find it useful. http://www.rebeccas-beads.com
Thank you Mr. Zeldman and other standards proponents.
Actually it’s IE that’s screwed up. Of course it represents the majority of browsers out there, so making sure things work on it is a good thing. But being able to code once and distribute to any client is the ideal. If IE were compliant, then we wouldn’t have to come up with so many hacks just to make a site behave as we expect.
Finally, if your site is any indication, then yes you are a very bad designer. But then you don’t care about that anyway do you Dante?
Hi, this may be really simple, but I was wondering if it’s possible to either make the image or caption a link? If so, an example would be greatly appreciated!
Frankly I don’t care about people calling my design bad anymore. People like you don’t visit my site, anyway. My site was aimed at people looking for info on San Francisco History, which flowed smoothly. Maybe that failed, but I’m fixing it. So go ahead and sue me for trying to help people.
Ian, just wanted to express my (belated but still very) sincere thanks to you for figuring out what was wrong with my script there.
Your suggestions worked perfectly, and they taught me a _lot_ of valuable stuff about JavaScript and the DOM. Thanks many bunches.
I don’t help people. I give maymay a lot of advice, even though I didn’t solve it. And no thank yous.
Just kidding.
Awesome script! Just what I’ve been looking for.
I’ve been trying to figure out where I can add a bookmark tag somewhere on this script, so whenever I click on an image it will display and also make a call to the bookmark on the page.
Thanks first.
I think this is a great little script. I was just wondering if it would be difficult to make the image that javascript intercepts a link to a larger image. So, when I click on the text link it shows the preview, and then when the preview is clicked (the link that javascript intercepts) it opens a larger version of that image in a new window.
thanks
I applied the techniques in this article to an existing page, and I must have some simple puncuation in the code wrong (even though I cut and pasted most of it)
Does anyone have a working sample of these gallery using image thumbnails? I may be able to get mine working by looking at someone else’s.
Is it possibile to link the target image to a larger version of the image?
Thanks
Paul: I successfully executed using thumbnails on this site: http://summerinnbnb.com/haines.php
An interesting note about the caption area… I found that if your placeholder text is say two lines long, and you replace it with a caption that’s 3 lines long you may run into issues with some browsers (Safari being one of them, didn’t test beyond that). The issue I ran into was that the third line gets cut off when you click on an image with a 3 line caption. I kinda had to hack to fix it – by forcing my placeholder text to be extra large, adding a few br’s and a non-breaking space.
Is it possible to format the caption area at all, like adding a
in the caption?
Great article, thanks again ALA. I did find a problem in Safari though. If your images are not exactly the same size they will be stretched, matching the size of the largest image (I tried it with images of same height different widths, but assume the reverse is also true). I did not specify height or width in code (exactly the same as in the article) & it works fine in IE5.5 Win, Win/Mac Firbird/Firefox, and Camino. I did not change the javascript at all, just copy and paste from the article. I am running Panther 10.3.3, Safari 1.2.1.
This may be a fairly basic problem for those with more experience, but being new to JavaScripting….
What I would like is to have the caption provided not by the Title element, but instead along the lines of a PHP include?
I guess pseudo-code for this would look something like this…
01
…where I assume myCaption would be a text string passed to a function within the JavaScript that would then display the contents of the file 01.txt.
Is this sort of thing possible? Either code and/or pointers to resources/examples would be appreciated.
Thanks for taking the time to write this article. Its been quite helpful.
Brooks
Hey Jeremy, thanks for that – _very_ useful – and I even substituted thumnails for the text and it looks neat, but I found a problem….
You say it works for IE 5+ (PC and Mac), but my version of IE (Mac 5.2.3) opens the larger images like they were a link to another page which means I lose all my lovely page formatting _and_ I’m forced to use the back button.
Any suggestions why it would do that?
Love this script and would like to use it. It’s not working for me in Netscape 7.1, and I just went through all the comments here. None of the examples work in NS7.1 (except for Rebecca’s beads – absolutely beautiful, by the way!) Works fine in IE6 and Moz.
Here’s my attempt:
http://garfieldz.com/chgo2004-alagallerytest.html
Here’s a screenshot. I want it to look like it does in IE:
http://garfieldz.com/chgo2004-alagallery-screenshot.html
Would appreciate some help! Thanks!
My bad! There was a problem with my NS profile. AOK now. Love the script! Thanks!
I also love this image gallery. I really need these previous / next buttons though. I thought maybe this can be accomplished using a bit of javascript and using display:none? Or changing the Z-index using javascript? Does anybody know how to do that?
Please only use the following browsers in your comparisons.
IE 6.1 (fully patched)
Opera 7.5b/7.23
Mozilla 1.7b
Firefox 0.8
Safari (1.2)
In case you didn’t know IE 3,4,5, Netscape 4,4.6,4.08,6 are obsolete so let’s not say i hope it can work in any of them.
Are we ever going to move forward. I might as well bring out my betamax video machine so i can watch the latest Matrix dvd disc on it, watch me start crying when i can’t insert the disc.