1
\$\begingroup\$

How can I rewrite this in a simpler way?

$imageContainer = $($(this).parent().children()[0]).children()
currentIdx = 0
for e, idx in $imageContainer
  if e.className.indexOf('active')
    currentIdx = idx
    break
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Could you describe what this code does? \$\endgroup\$
    – Jamal
    Commented Jul 8, 2014 at 3:52
  • 1
    \$\begingroup\$ Also we would like to know the context of $(this) \$\endgroup\$
    – Shaunak D
    Commented Jul 8, 2014 at 4:00
  • \$\begingroup\$ @Jamal Im navigating around ul li and looking the active state on the current slide (is a carousel) \$\endgroup\$
    – r23712
    Commented Jul 8, 2014 at 4:06

1 Answer 1

2
\$\begingroup\$

It looks like you're looking for the index of the first child of $imageContainer with the active class. (Incidentally, your code will also trigger on stuff like inactive, which might be a false positive. Be careful about your classes!)

Native selectors work fine here. Furthermore, your initial assignment doesn't do things the jQuery way -- there's no reason to initialise two separate jQuery objects. Try replacing your block with something like:

$imageContainer = $(this).parent().children().first().children()
currentIdx = $imageContainer.index($imageContainer.filter(".active"))

Better yet, instead of that monstrous .parent().children().first().children(), give it a meaningful ID or class, so you can just do $imageContainer = $(".image-container", this).

If you can guarantee that the ul will contain only lis, then you can simplify further to currentIdx = $imageContainer.filter(".active").index().

Depending on your exact situation, you may even be able to replace everything with the one liner:

currentIdx = $(this).parent().find(".active").index()
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.