Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the Correct Way to Access Array Elements in jQuery?

Tags:

arrays

jquery

I have two arrays. One is for a navigation, the other is for panels on the page. The arrays are both the same size. One nav button for one panel. This code works, but I'm sure there must be a better way to do this without setting up the temporary variables.

$('.footer-nav li').click(function()
{
  var temp = $('.footer-nav li').index(this);
  var tArray = $('.about-bgs li');
  $('.about-bgs li').fadeOut();
  $(tArray[temp]).fadeIn();  //This is the line in question!
});

Any takers?

like image 262
Joshua Creed Gilmer Avatar asked Nov 04 '22 15:11

Joshua Creed Gilmer


1 Answers

The jQuery callback to $(selector).each(callback) accepts two parameters: index and element. So you can write

$('.footer-nav li').each(function(index, element) {
  element.click( function(evt) {
    $('.about-bgs li').fadeOut();
    $('.about-bgs li').get(index).fadeIn();
  }); 
});

But this seems a strange code to me, since there are animation conflicts between all of the elements in the list (which are fading out) and the designated one (which is fading in). I think it won't work as expected.

Since it seems that only one element is visible at a time, I'd fade out only the currently visible one (not to say that you need to check for two consecutive clicks on the same element):

var current = $('.about-bgs li').fadeOut();
var last = $('.about-bgs li .current');
if (current !== last) {
  last.removeClass('current').fadeOut();
  current.addClass('current').fadeIn();
}

Upon DOM loading time you must designate a .current element and run this function (or playing with CSS/JS accordingly).

like image 178
Raffaele Avatar answered Nov 09 '22 11:11

Raffaele