0

This answer by sg3s on how to use jQuery (from someone's question) to slide divs horizontally is exactly what I want to do. However, I can't for the life of me figure out the jQuery code.

jQuery(function($) {

$('a.panel').click(function() {
    var $target = $($(this).attr('href')),
        $other = $target.siblings('.active');

    if (!$target.hasClass('active')) {
        $other.each(function(index, self) {
            var $this = $(this);
            $this.removeClass('active').animate({
                left: $this.width()
            }, 500);
        });

        $target.addClass('active').show().css({
            left: -($target.width())
        }).animate({
            left: 0
        }, 500);
    }
});
});

I get stuck on the if statement and the reason for the active class and .animate on both statements within it. Can someone please run me through this bit of jQuery? Instead of just using the solution, I'd love to understand it.

Thanks!

Community
  • 1
  • 1
ObbyOss
  • 357
  • 1
  • 2
  • 14

1 Answers1

1

On click on an a.panel element, declare a variable for the clicked element $target and the clicked elements siblings $other on the DOM tree,

  1. If the clicked element does not has the active class
    • For every sibling, ($other.each())
      1. Remove the active class from siblings and
      2. Move them to the left equal to the pixel width of each sibling (hide)
    • For the clicked element ($target)
      1. Add the active class (.addClass('active'))
      2. Move to the right equal to the pixel width of the clicked element (show)

jQuery's each() function is very much like forEach() on plain Arrays, except it also works with jQuery objects, which is what $target and $other are in this code sample.

The if statement if (!$target.hasClass('active')), given the logic of the sample, will avoid running this animation code if the user clicks on the already active element.

Finally, jQuery implicitly changes the meaning of this inside functions passed to it, in as such that this inside a function passed to each() or click() will be the current HTMLElement.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • Thanks for the wonderful breakdown! Final question: I don't see an active class, hence one of my confusions. Is the active class simply there to identify which links was clicked? Or am I just missing something big? – ObbyOss May 02 '15 at 05:35
  • More or less, based on the logic in the sample. – jdphenix May 02 '15 at 05:37