Reputation: 778
This is the code to store five images for an HTML page and then the function is used to display those five images one at a time.
This code works and one can scroll through the five images.
My question is whether it is possible to direct to different HTML page on the basis of image shown at a particular time
<script type="text/javascript">
var curImage = 0;
var cImages = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
function townHousePics(direction) {
if (direction == 'next') {
curImage++;
if (curImage == 5) {
curImage = 0;
}
}
else
{
curImage--;
// even reset the counter here when
// its getting 0
}
document.images[0].src = cImages[curImage];
}
</script>
Upvotes: 1
Views: 2162
Reputation: 268324
Suppose you had a link like the following:
<a href="1.html" id="viewLarge">View Large</a>
That you wanted to dynamically change with each image. When image 2.jpg becomes the primary, we swap out 1.html for 2.html. We could modify the last line of your code to this:
// Updated Source of First Image
document.images[0].src = cImages[curImage];
// Parse Image Number from String
var currentNumber = parseInt( curImage, 10 ); // 2.jpg becomes 2
// Get a reference to our 'viewLarge' link
var ourLink = document.getElementById("viewLarge");
// 1.html becomes 2.html when 2 is the currentNumber;
ourLink.href = ourLink.href.replace( /^([0-9]+)/, currentNumber );
Note, though this works it restricts you to having a 1.html
for your 1.jpg
. This may be undesirable. You may want 1.jpg
to go with CityLoft.html
. If that's the case, you'd want to associate the image with the proper url in your cImages
object:
var cImages = [{image: '1.jpg', page: 'cityLoft.html'},
{image: '2.jpg', page: 'townhome.html'}];
Once you've made this change, you only need to restore the references in your code. For instance, we would change the following:
document.images[0].src = cImages[curImage];
To this:
document.images[0].src = cImages[curImage].image;
We would also need to update our code that links to the relevant page as well:
document.getElementById("viewLarge").href = cImages[curImage].page;
That's it!
Upvotes: 1
Reputation: 6011
<a href='' id='my-anchor-name'><img id='my-image-name' src=''/></a>
<script type="text/javascript">
var curImage = 0;
var cImages = [{aHref:'target1.html',imgHref:'1.jpg'},{aHref:'target2.html',imgHref:'2.jpg'},
{aHref:'target3.html',imgHref:'3.jpg'},
{aHref:'target4.html',imgHref:'4.jpg'},
{aHref:'target5.html',imgHref:'5.jpg'}
];
function townHousePics(direction) {
if (direction == 'next') {
curImage = (curImage++)%cImages.length ;
else {
curimage = (curImage--)%cImages.length;
}
var img = document.getElementById('my-image-name');
var anchor = document.getElementById('my-anchor-name')
img.src = cImages[curImage].imgHref;
anchor.href = cImage[curImage].aHref;
}
</script>
Upvotes: 2