change image based on page title

Soldato
Joined
26 Aug 2004
Posts
7,571
Location
London
I'm wanting to set an image on a page depending on the page title eg if you were viewing boats.htm it would show boats.jpg, or on cars.htm it would show cars.jpg.

I've done some googling, but, tbh, I've no idea where to even start.

A push in the right direction would be greatly appreciated.
 
As you're seemingly serving up static pages, what's preventing you from manually editing the filenames?

Anyway, I wrote a quick and ugly bit of JS to grab the filename (e.g. 'boats' from boats.html):

Code:
var file = document.URL.split('/').pop().split('.').shift();

Just send it to the image's src attribute. Won't work if your filename contains a period.
 
Yes they're static pages. I figured it would be a lot easier to have a single snippet of code that changed the picture to the name of the page than change the source for an image for every new page that I create.

Using what you posted I've tried this
Code:
<script language="JavaScript1.2">

<!--
var picsource = document.URL.split('/').pop().split('.').shift();
//-->

</script>

<img src= picsource & ".jpg" alt="" name="photo" width="32" height="32" id="photo" />

It doesn't seem to work though - am not completely sure what I'm doing wrong.
 
thanks to you setting me off on the right course I've now worked it out
Code:
<script language="JavaScript">
<!--
function setimage()
{
var picsource = document.URL.split('/').pop().split('.').shift();
var str=picsource +'.jpg';
document.images['imgphoto'].src=str;
}
</script>

Many thanks
 
Last edited:
If you have different pages, what's wrong with adding an id to the body tag and changing the image in the CSS?
 
Nothing wrong with doing it that way - I hadn't actually considered doing that. I guess that way would lead to a slightly longer css file and thus take (very very) slightly longer for the page to load, but the main disadvantage would be when I start having loads of pages - the file could start getting really really long. This way I just need to remember to dump a file in the directory with the same name.
 
Given the size of a CSS file anyway for any large-ish website a few lines is nothing...

Code:
#boat element{

background: url(path/to/image) no-repeat;
}

or even

Code:
#boat element {background: url(path/to/image) no-repeat;}

Not a lot is it? You also avoid the problem if someone has javascript switched off. Slightly more work if you change image name/add an image but I would have thought if something can be done in CSS why use javascript?
 
i'd do it with php (if you have it of course)

Code:
<img src="<?php echo basename($_SERVER['SCRIPT_NAME'], '.php'); ?>.jpg" alt="image">
 
Actually that is quite elegant. Better than javascript as you aren't relying on browser config. Probably the best option yet. Followed by CSS :p
 
Back
Top Bottom