1

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!

Michael Vattuone
  • 318
  • 1
  • 6
  • 17
  • What does the `return Slider;` belong to at the end of the main code block? (You don't show the beginning of the function that ends right after that `return`.) Having `$('.slideshow').click(...);` inside the `Slider()` constructor is going to bind additional clicks on every `.slideshow` element every time the constructor is called. – nnnnnn Jan 25 '13 at 23:23
  • Would this question be better off on [**CodeReview Stack Exchange**](http://codereview.stackexchange.com)? I'm only asking cause I think for SO directly this question might be to broad and might not fit the expected [**Q&A**](http://stackoverflow.com/faq#questions) format. I'm just trying to make sure you get the desired answers rather than potentially getting the question closed as not constructive or similar. – Nope Jan 25 '13 at 23:28
  • That's a whole mess of Javascript. Please remove irrelevant code from your code samples, you're likely to get more answers that way. Also, avoid complex compound answers. – millimoose Jan 25 '13 at 23:45
  • Thanks guys - I apologize for the messy code. I've removed what I thought wasn't relevant to the question and fixed some careless typos. Hopefully it is less confusing. If this is more a **[CodeReview Stack Exchange](http://codereview.stackexchange.com/)** type of question, I am happy to move it there. – Michael Vattuone Jan 25 '13 at 23:55

1 Answers1

2

This bit of code attaches a click handler to all .slideshow elements in the document.

$('.slideshow').click(function(e) {
    e.preventDefault();
    return _this.prev();
});

What you might have wanted was to attach the handler only to the .slideshow elements that are descendants of the slider:

this.slider.find('.slideshow').click(function(e) {
    // ... handle event here ...
});

Now, about your on() statement:

$('.slideshow a.next').on("click", function(e) {
   e.preventDefault();
   $('.slideshow').each(function() {
     _this.prev();
   }
});

What you've done here is bind a click event handler to all the .slideshow a.next elements, and what the handler does is run _prev() on all of them. But you already have another handler bound to the .slideshow element from when you called $('.slideshow').click(). When the "on" handler is finished, the event continues to propagate up the DOM tree, triggering all of the click handlers on its way up, including the one you bound to the .slideshow element. And of course that handler also calls _prev().

If you want to stop event propagation, you have two choices.

  1. call e.stopPropagation()
  2. return false from your event handler (this tells jQuery to stop propagation and prevent the default action).

You may ask yourself, "what is the difference between click() and on('click', ...). The on() method lets you use Event Delegation. Basically, that means using a single event handler attached to one DOM node to handle events on a lot of descendant elements.

As an example, imagine you have a div with some arbitrary number of images in it, and you need to do something whenever an image is clicked. You can either (a) bind a click event handler to each image or (b) bind a handler to the div that will handle all the click events for all the images as those events bubble up the DOM tree.

$('#imageDiv').on('click', 'img', function(evt) {
    // ... "this" is the image that was clicked ...
});

Delegation has the added benefit that you can add and remove images from the container, and the delegate will continue to work.

Community
  • 1
  • 1
slashingweapon
  • 9,899
  • 3
  • 25
  • 46
  • 1
    Good answer. The propagation is usually called event bubbling (the opposite is known as event capturing). http://www.quirksmode.org/js/events_order.html – Ryan Smith Jan 25 '13 at 23:57
  • I made a mistake in my initial question, the first function should have been `$('.slideViewport a.next').click(function(e) { e.preventDefault(); return _this.next(); });` Update: That article is GREAT. Thank you Ryan! – Michael Vattuone Jan 25 '13 at 23:58