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!
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,
active
class
$other.each()
)
active
class from siblings and$target
)
active
class (.addClass('active')
)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
.