0

The following code is part of a jQuery .js-file (which is used in the "supersized" image slider):

if (vars.current_slide == 0) {
 $("#captions").children().css("display", "none");
    $("#caption0").css("display","inherit").css("visibility","visible");
    } 
if (vars.current_slide == 1) {
 $("#captions").children().css("display", "none");
    $("#caption1").css("display","inherit").css("visibility","visible");
    } 
if (vars.current_slide == 2) {
 $("#captions").children().css("display", "none");
    $("#caption2").css("display","inherit").css("visibility","visible");
    } 

As you can see, I tried to show a different caption (ranging from #caption0 to #caption3) for each current_slide.

How do I shorten this so that the caption for each current_slide is assigned via a variable, unlike my example?

3 Answers 3

4

The selector is just an ordinary string, so you can concatenate the variable like this:

$("#caption" + vars.current_slide)

So in your case, the code could be shortened to:

$("#captions").children().css("display", "none");
$("#caption" + vars.current_slide).css("display","inherit").css("visibility","visible");

Or even shorter:

$("#captions").children().hide();
$("#caption" + vars.current_slide).show();
Sign up to request clarification or add additional context in comments.

1 Comment

Great stuff, this worked for me. Thank you for the fast answer :)! Also thanks to the others ;).
2

Try:

$("#caption" + vars.current_slide)

An alternative would be putting the elements into an array and accessing it by index

Comments

1

Just append the variable to the string:

$('#captions').children().hide();
  $('#caption' + vars.current_slide).css({
    'display': 'inherit',
    'visibility': 'visible'
   });
} 

Comments

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.