Umair Jameel Umair Jameel - 2 months ago 6
jQuery Question

JQuery Plugin's Separate Scope for Each Element

I am developing a carousel jquery plugin. I am trying to call with more than one carousel div element like

<div class="carousel-container">...</div>
<div class="carousel-container2">...</div>
...


Where I am calling plugin

$(".carousel-container").mycarousel({
// Properties
});

$(".carousel-container2").mycarousel({
// Properties
});


Plugin Code:

(function($) {
$.fn.mycarousel = function(options) {
var settings = $.extend({
indicators : true,
autoplay : true,
autoplayDir : "forward",
slidesToShow : 1,
slidesToScroll : 1
}, options);

return this.each(function() {
// JavaScript code like constructor function and its prototypes

// variable declarations and initialization
var outerCarouseWidth, imageWidth;
var elements, carousel;
...

// jquery code for selectors, events etc.
var carouselInner = $(".carousel-inner");
var carouselOuter = $(".carousel-outer");
...

$(".next-link").on("click", function(e) {
slide("next", "first");
});
...
});
};
}(jQuery));


Well, right now I am trying to access child elements using $(this) within each function. Like $(this).children()[0].text("abc").

The Problem I am facing here is that, both carousel div elements are sharing the scope of variables, selectors etc. When I slide one carousel, other carousel moves as well and facing some other technical issues. How can I separate the scope of code of jquery plugin for each element with which I am calling this plugin?

Answer

Scope the finding of elements to the current element that the plugin is applied upon.

Use carouselEl as the parent selector for all sub elements.

Like this:

```

return this.each(function() {
  var carouselEl = $(this);
  ...

  // jquery code for selectors, events etc.
  var carouselInner = carouselEl.find(".carousel-inner");
  var carouselOuter = carouselEl.find(".carousel-outer");
  ...

  carouselEl.find(".next-link").on("click", function(e) {

        slide(carouselEl, "next", "first"); // This must also be scoped.. I cant see the code for this function. 
  });
  ...
});

```

Comments