1

I have a plugin that reacts on mousemove, and if i call second instance of same plugin, it ovewrites bindings of first call. How do i create plugin that can use same event with different settings?

(function($, document){
  $.fn.parallax = function(options){    
    options = $.extend({
        speed: .4,
        speedY: .2,
        random: false
    }, options);
    $this = this;
    var cursor = {};
    cursor.delta = {};
    cursor.X = 0;
    cursor.Y = 0;

    $this.children().each(function(ind, layer) {                
        if (options.random) {
            $(layer).data("speedX",Math.random()*options.speed);
            $(layer).data("speedY",Math.random()*options.speedY);
        };
    }) 

    $(document).mousemove(function(event) { 
        cursor.delta.X =  $this.offset().left - cursor.X;
        cursor.delta.Y =  $this.offset().top - cursor.Y;
        cursor.X = +event.pageX;
        cursor.Y = +event.pageY;      
        $this.children().each(function(ind, layer) {                
            startX = +$(layer).css("left");
            startY = +$(layer).css("top");
            speedX = $(layer).data("speedX")?$(layer).data("speedX"):options.speed;
            speedY = $(layer).data("speedY")?$(layer).data("speedY"):options.speedY;               

            $(layer).css({
                transform : "translate("+ (cursor.delta.X*speedX) +"px, "+ (cursor.delta.Y*speedY) +"px)"
            },100);
        }) 
        console.log($this);      

    }); 
    return this;

  };
})(jQuery, document);
Winni
  • 85
  • 1
  • 7

1 Answers1

0

Problem was here:

$this = this;

js created global $this, and overwrote it on second call. Solution is var, it will create local $this, and will change them accordingly

var $this = this;  

More over you can avoid this kind of problem by introduce 'use strict' mode which will throw error when unsafe actions are taken such as gaining access to the global object.

Community
  • 1
  • 1
Winni
  • 85
  • 1
  • 7