I need some guidance in understanding why these functions are doing what they are doing...
1.) On my web page, I have three different panels that utilize a Slider function, which creates an unordered list that has slider functionality using next and previous anchor links. See the code below:
function Slider(id) {
var _this = this;
this.id = id;
if (!id) return false;
this.index = 0;
this.slider = $(this.id);
this.length = this.slider.children().length;
this.width = $(this.id).outerWidth();
this.totalWidth = this.length * this.width;
$(id).addClass('slideWrapper').wrap('<div class="slideViewport">').after('<div class="sliderNav"><a href="#" class="prev">Previous</a><a href="#" class="next">Next</a></div>').css({
'width': this.totalWidth
}).children().addClass('slide').css({
'width': this.width
});
$('.slideViewport a.next').click(function(e) {
e.preventDefault();
return _this.next();
});
$('.slideViewport a.prev').on(function(e) {
e.preventDefault();
return _this.prev();
});
}
If I try to run more than one of these Slider instances on a page, clicking a .next anchor will cause the clicked element and any of the elements below it to more to the next list element in their slideshows. Going to the second panel would cause all but the first to run, the third panel causes all but the first and second to run, etc. I would have expected the handler to only run for the event that I clicked on, rather than all instances of the class after it, since I am using this
in my event. Any explanation as to what is going on here would be immensely helpful.
2.) Now, I've been trying to make it such that all of the Slider events DO run next() when I click on any a.next anchor on the page, rather than just run an event for the one whose anchor I have clicked. I have figured out that this code works:
$('.slideshow').on("click", "a.next", function(e) {
e.preventDefault();
return _this.prev();
});
But truth me told, I'm not really sure why this is working. My understanding is that JQuery is only looking to see if the a.next anchor is clicked, and will then pass the handling function to the $('.slideshow') selector, which makes me assume that it is selecting all instances of $('slideshow') and running the .next() function for all of them. Is that the right way to think about it?
3.) Why does the following snippet of code cause all of the slideshows to run the next() function twice, as opposed to once? I don't really like that this isn't returning anything, so I don't really want to use this particular bit of code, but I'd just like to understand it a little bit better...
$('.slideViewport a.next').on("click", function(e) {
e.preventDefault();
$('.slideshow').each(function() {
_this.prev();
}
});
Help understanding any of this code would be much appreciated. I would really like to have a better understanding of what is going on in the DOM in terms of propagation in this scenario, but everything I've tried to read has just made me feel more confused. Thanks!