2

I'm making a simple slider. It has a carousel navigation bar with small photos. Photo:

enter image description here

When you click on small image the big one schould change to the image of small one. I don't want to write separate events for each small photo. I would like to create them all in one for loop.

I tried so far:

function photo(nr) {
    var photoNr = '<img class="bigFoto" src="images/'+nr+'.jpg">'
    $('div.bigFotoContainer').html(photoNr);
}

function outIn() {
    $('div.bigFotoContainer').fadeOut(500);
    $('div.bigFotoContainer').fadeIn(500);
}

for(var i=1; i<18; i++) {
    $('.Photo'+i.toString()).click(function(){
        outIn();
        setTimeout('photo('+i+')',500);
    });
}

This solution doesn't give out any image. It makes an error:

"Failed to load resource: the server responded with a status of 404 (Not Found)"

I am thankful for the help.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Czapa
  • 73
  • 1
  • 1
  • 6

1 Answers1

1

It's not a good procatice to attach event inside a loop when you could use common classes or also you could use the start with selector ^ :

$('[class^="Photo"]').click(function(){
    // Your code here
});

That will attach the click event to all the elements with the class that start with Photo.

Or you could use a separated function (for example click_event) :

for(var i=1; i<18; i++) {
    click_event(i);
}

function click_event(i){
    $('.Photo'+i.toString()).click(function(){
        outIn();
        setTimeout('photo('+i+')',500);
    });
}

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101