3
\$\begingroup\$

I've been steadily improving a show many move one carousel sample that I found a few weeks ago. I want to post my improvements for others to use but don't want to spread bad code. I'm not an expert in JavaScript but I always like to produce clean code.

Working demo

(function(){
 $('.carousel-showmanymoveone .item').each(function(){
 var itemToClone = $(this);
 for (var i=1;i<4;i++) {
 itemToClone = itemToClone.next();
 // wrap around if at end of item collection
 if (!itemToClone.length) {
 itemToClone = $(this).siblings(':first');
 }
 // grab item, clone, add marker class, add to collection
 itemToClone.children(':first-child').clone()
 .addClass("cloneditem-"+(i))
 .appendTo($(this));
 }
 });
}());

Thoughts

I've done all the improvements I can think of but:

  • I'm wondering about seeing $(this) appear twice.
  • Are the siblings, children, :first-child, :first usages the best options?
  • Any other improvements or best practices I've missed?

Is there something I could do better?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 27, 2015 at 9:52
\$\endgroup\$
2
  • \$\begingroup\$ I'm satisfied siblings is the best option \$\endgroup\$ Commented Mar 27, 2015 at 10:04
  • \$\begingroup\$ Looks pretty clean for me. the only improvement that I will make , will be extract in a varible, after .clone() \$\endgroup\$ Commented Mar 27, 2015 at 13:27

1 Answer 1

1
\$\begingroup\$

Thanks for looking at this. I have concluded that I am happy with the code.

To incorporate the valid suggest by @vmariano, I have split this off into its own variable. This does make sense from a best-practices viewpoint as once I clone the item it is no longer itemToClone it is a clonedItem.

Final code:

(function(){
 $('.carousel-showmanymoveone .item').each(function(){
 var itemToClone = $(this);
 for (var i=1;i<4;i++) {
 itemToClone = itemToClone.next();
 // wrap around if at end of item collection
 if (!itemToClone.length) {
 itemToClone = $(this).siblings(':first');
 }
 // grab item, clone, add marker class, add to collection
 var clonedItem = itemToClone.children(':first-child').clone();
 clonedItem.addClass("cloneditem-"+(i))
 .appendTo($(this));
 }
 });
}());
answered Mar 31, 2015 at 14:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.