PDA

View Full Version : Javascript: if/then random image rotator...




Sdashiki
Sep 21, 2009, 07:41 AM
Right now all pages on the site rotate the same 7 images. To break this up I made multiple versions of the code below. One version for each "section" of the site.

randomNumber is a var set earlier in the code so that the max# of images in the folder is set.

The randomizer is a script within the header section of the site, it writes the <img> tag:
document.writeln('<IMG SRC="http://site/imagefolder1/image0' + randomNumber + '.jpg" ');

What I would like is instead of multiple versions of the code, just an if/then/else adjustment of the code so that it will check the location of the current url and based on it choose the right /imagefolder#/ for that set of pages.

The site is setup so that subfolders such as
http://www.thesite.com/section/
http://www.thesite.com/section2/
are what the javascript needs to check. Is the current url part of this section (i.e. are you in this subfolder of the site)?

Im drawing a blank as to how to go about doing this but it seems so straightforward. Googling for a specific answer is proving difficult when I cant seem to keyword what Im looking for properly. THANKS!



angelwatt
Sep 21, 2009, 09:03 AM
Here's some code to work from. Using regex to find out if in a certain area. There should be a \ in front of the W in the if statement. They get parsed out for posts.

function Init() {
var loc = window.location;
if (/section\W/.test(loc)) { alert('Section 1'); }
else if (/section2/.test(loc)) { alert('Section 2'); }
else if (/section3/.test(loc)) { alert('Section 3'); }
else { alert('Default'); }
}

Sdashiki
Sep 21, 2009, 02:27 PM
After racking my brains more this afternoon, I decided to switch to a PHP script.

Got everything working great now, but thanks for the effort!