0

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
  • var images = { 10: 'image.jpg', ..., }, defaultImg = 'image-2.jpg; Commented Mar 12, 2015 at 22:35
  • On button click what is your exact need? Commented Mar 13, 2015 at 9:22

2 Answers 2

2

One solution is to use the variable as part of the image name, e.g.

 $('img').attr('src','img/image-' + variable + '.jpg');
Sign up to request clarification or add additional context in comments.

Comments

1

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

I did understand what you said, but I don't know how to execute it, so I'll be doing this: instead of putting $('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!
if your image names are in a row, does a loop solves the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.