Yeah this might look crazy but I just want to know if this is possible or not. I have something like this:
$('button').click(function(){
if(variable == 10){
$('img').attr('src','img/image.jpg');
} else {
$('img').attr('src','img/image-2.jpg');
}
});
Now, the problem is I have more than 2 photos (I have 10 categories of 2 photos each) but I don't want to create 10 variables and copy that block of code 10 times. So I wondered if you can make something like changing that 'img/image...jpg' part with another javascript command or so.
2 Answers 2
One solution is to use the variable as part of the image name, e.g.
$('img').attr('src','img/image-' + variable + '.jpg');
Comments
It depends on the names of your images - if you control the names, then you can make them work better with dynamic variables using a concept called string concatenation:
var num = 2;
$('img').attr('src', 'img/image-' + num + '.jpg');
This code will render img/image-2.jpg. If you change the num variable, the image source will change accordingly.
2 Comments
$('img').attr('src','img/image.jpg'); inside I'll put a variable with it so I can change the value of the variable, thanks anyway for replying!
var images = { 10: 'image.jpg', ..., }, defaultImg = 'image-2.jpg;