Stephan - the curious
Stephan - the curious

Reputation: 423

Strange js behaviour of image gallery

Hi there, I would like to build an image gallery with pure javascript and found a quite good approach http://www.trans4mind.com/personal_development/JavaScript/imageSlideShow.htm.

However, it does not work as expected. Even though I managed to link my Next / Back buttons to switch the images in the array the second image would only appears for a fraction of a second before reverting back to the initial image.

Is there anything messed up in the js?

currentIndex = 0;

MyImages = new Array();

MyImages[0] ="images/sampleimage.jpg";
MyImages[1] ="images/kuh.jpg";


function preload()
{
    for (var i=0;i<MyImages.length;i++){
        var imagesPreloaded = new Image();
        imagesPreloaded.src = MyImages[i];
    }
}

preload();


function Nexter(){
if (currentIndex<MyImages.length-1){
    currentIndex=currentIndex+1;
    document.theImage.src=MyImages[currentIndex];
}
else {
    currentIndex=0;
    document.theImage.src=MyImages[currentIndex];
}
}

function Backer(){
if (currentIndex>0){
    currentIndex=currentIndex-1;
    document.theImage.src=MyImages[currentIndex];
}
else {
    currentIndex=1;
    document.theImage.src=MyImages[currentIndex];
}

}

$("#nav_left").on("click",function(){
    Nexter();
});

$("#nav_right").on("click",function(){
    Backer();
});



//
//img Gallery
//


$(".gallery_nav img").on("mouseover", function (){
    $(this).css("opacity", 0.8);    
});

$(".gallery_nav img").on("mouseleave", function (){
    $(this).css("opacity", 0.1);
});

Thanks for any useful hints. And BTW: Firebug tells me the following in the console:

Image corrupt or truncated:

Finally, the code above is the maximum extent of js I can deal with at the moment regarding my current level of knowledge and expertise. So please consider this when answering

Upvotes: 0

Views: 106

Answers (1)

Dogoferis
Dogoferis

Reputation: 614

It looks like the markup of your our link tags () is jacking up or possibly reloading the page - which would reset the gallery back to image #1. Try adding a # to the href attribute of your link markup (to denote them as anchors) or just flat out change them to tags

Example
    <a href="#" class="gallery_nav" id="nav_left"><img src="images/pfeil_links.svg" alt="First image"></a>

here is an altered JSFiddle that seems to work okay http://jsfiddle.net/Nf7yR/1/

And here is a version that uses spans; to the same effect: http://jsfiddle.net/Nf7yR/2/

Upvotes: 1

Related Questions