Pejman
Pejman

Reputation: 2636

JQuery .animate() in plugin

I create this plugin but when i use it on 2 different selectors: $('.1').Breath() and $('.2').Breath() it's not workin fine and when i stop it on one of selectors:$('.1').BreathStop() animate of all selectors going to stop. I don't know what is the problem

(function($) {
  var breathing;
  $.fn.Breath = function() {

    var options = $.extend({
      minOpacity: 0,
      maxOpacity: 1,
      BreathIn  : 1000,
      BreathOut : 3000
    }, arguments[0]);

    return this.each(function() {
      breathing = true;
      var obj = $(this);
      function breath() {
        if(stop()) return;
        obj.stop().animate({
          opacity: options.minOpacity
        }, options.BreathOut, function() {
          if(stop()) return;
          obj.stop().animate({
            opacity: options.maxOpacity
          }, options.BreathIn, function() {
            if(stop()) return;
            obj.stop();
            breath();
          });
        });
      }

      breath();

      function stop() {
        if(!breathing)
          obj.stop().css({opacity: 1});
        return !breathing;
      }
    });
  }

  $.fn.BreathStop = function() {
    breathing = false;
  }

})(jQuery);

Is there any solution?

Upvotes: 1

Views: 224

Answers (1)

mishik
mishik

Reputation: 10003

You need to "localize" your breathing variable. Currently it is common for all the elements using your plugin.

The easiest way that comes to my mind is using element's data:

(function($) {

    $.fn.Breath = function() {

        var options = $.extend({
            minOpacity: 0,
            maxOpacity: 1,
            BreathIn: 1000,
            BreathOut: 3000
        }, arguments[0]);
        return this.each(function() {
            var obj = $(this);
            obj.data("breathing", true);

            function breath() {
                if (stop()) return;
                obj.stop().animate({
                    opacity: options.minOpacity
                }, options.BreathOut, function() {
                    if (stop()) return;
                    obj.stop().animate({
                        opacity: options.maxOpacity
                    }, options.BreathIn, function() {
                        if (stop()) return;
                        obj.stop();
                        breath();
                    });
                });
            }
            breath();

            function stop() {
                if (!obj.data("breathing")) obj.stop().css({
                    opacity: 1
                });
                return !obj.data("breathing");
            }
        });
    }
    $.fn.BreathStop = function() {
        this.each(function() {
            $(this).data("breathing", false);
        });
    }
})(jQuery);

Upvotes: 1

Related Questions