0

This might be simple thing but just can't figure it out.

Let's assume I got fifty similar functions and there's two of them:

var unit = ['red', 'pink']
var unit2 = ['red2', 'red2']

$('#red').click(function() {
if($('#red2').is(':hidden')) {
$('#red2').toggle();
} else {
$('#red2').toggle();}}}

and

$('#pink').click(function() {
if($('#pink2').is(':hidden')) {
$('#pink2').toggle();
} else {
$('#pink').toggle();}}}

and I want to add all these functions in one/two for loops. I tried this:

for (var i = 0; i < unit.length; i++) {
for (var y = 0; y < unit2.length; y++) {
$('#i').click(function() {
if($('#y').is(':hidden')) {
$('#y').toggle();
} else {
$('#y').toggle();}}}}
1
  • I'm sorry, but why do you even need if when the code in its branches is identical? Commented Sep 29, 2013 at 21:28

2 Answers 2

2

.toggle() method detects the visibility of the element itself, there is no need to use if statement, you can use this keyword which refers to the clicked element:

$('#red, #pink').on('click', function() {
   // Based on the id property of the clicked element 
   // this selects #red2 or #pink2 element
   $('#' + this.id + '2').toggle();
});

Also note that $('#i') selects an element with ID of i, you should concatenate the strings:

$('#' + i).foo();
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the toggle() was there because I used earlier css('visibility','hidden') method. But this seems to fit my needs, thanks.
0

You should concatenate strings:

for (var i = 0; i < unit.length; i++) {
  $('#' + unit[i])
  .attr('data-dst', unit2[i])
  .click(function() {
    var dst = $(this).attr('data-dst');
    $('#' + dst).toogle();
  }
}

2 Comments

Loop variable problem!
y === unit2.length by the time the click handler will run.

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.