Matthew Ruddy
Matthew Ruddy

Reputation: 925

Help with jQuery plugin.. affecting all items not one

As it says in the title, having a problem with a little basic plugin. As you can see in the example below, there are two divs contains images. When you click the black box beneath either of them, it hides both divs, not the one it is within. Why is this? How can it be fixed..

Example: http://www.matthewruddy.com/slider/slider.html

Code Sample:

(function($){
$.fn.extend({

premiumSlider: function(options) {

  var defaults = {
    width: 520, // Set width
    height: 340, // Set height
    startImage: 0, // Choose start image
    tranSpeed: 800, // Time taken to transition between images
    pauseTime: 3000, // Time slider remains paused before transitioning
    autoPlay: true, // Play the slider on load; true/false
    pauseHover: true, // Pause the slider on mouse hover
    transition: 'Slide', // Transition style
    easing: 'easeInOutExpo', // Easing style (slide only)
    preload: true, // Whether or not to preload images
    preloadIcon: 'images/loading.gif',
    preloadColour: '#fff'
  }

      var options = $.extend(defaults, options);

  return this.each(function(){
      var vars = options;
      var obj = $(this);
      var stuff = obj.find('.slider-wrap');

      $('.icon').click(function(){
        obj.hide();
      });
  });
}
});
})(jQuery);

Upvotes: 1

Views: 112

Answers (3)

Rion Williams
Rion Williams

Reputation: 76557

It's because in your function here:

return this.each(function(){
      var vars = options;
      var obj = $(this);
      var stuff = obj.find('.slider-wrap');

      $('.icon').click(function(){
        obj.hide();
      });
  });

The line :

var stuff = obj.find('.slider-wrap');

is finding the class "slider-wrap", which both of the sliders use. You might want to consider hiding each of them separately.

Upvotes: 2

Chandu
Chandu

Reputation: 82903

Because you are not scoping the search when looking for .icon. Change the click function to as follows:

$('.icon', obj).click(function()
{         
 obj.hide();       
}
);

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32082

$('.icon').click(function(){
    obj.hide();
});

The problem is that the selector applies to both icons. You can fix that by using .children():

obj.children('.icon').click(function(){
    obj.hide();
});

If it were nested more deeply, you could use .find():

obj.find('.icon').click(function(){
    obj.hide();
});

Upvotes: 0

Related Questions