views:

143

answers:

3

I wrote a jQuery plugin to control animations for several images on the same page. The calls are initialized at the beginning as:

$("#image1").anims({top: "240px", left: "300px"});

$("#image2").anims({top: "160px", left: "430px"});

The anims plugin basically applies a bunch of animations on mouseover and mouseout (using hover) based on the top and left parameters supplied. However, once everything is loaded in Safari, mousing over #image2 causes #image1 to animate with the parameters set for #image2. Mousing over #image1 animates #image1, as it should, with the parameters set for #image1, as it should. In Firefox, it is the opposite. I guess it has to do with the order they loaded in or something.

What might I have done wrong? I use $(this) throughout the plugin for the animate() and other various calls.

A: 

I would double check all of the bullet points on this page: http://docs.jquery.com/Plugins/Authoring

  • Name your file jquery.[insert name of plugin].js, eg. jquery.debug.js
  • All new methods are attached to the jQuery.fn object, all functions to the jQuery object.
  • inside methods, 'this' is a reference to the current jQuery object.
  • Any methods or functions you attach must have a semicolon (;) at the end - otherwise the code will break when compressed.
  • Your method must return the jQuery object, unless explicity noted otherwise.
  • You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way.
  • Always use jQuery instead of $ inside your plugin code - that allows users to change the alias for jQuery in a single place. See below for an explanation and a more elegant solution.

For example, you say you are using $(this) but you should be using jQuery(this). I doubt that that is the problem, but you should follow the documentation closely just in case there are some unexpected behaviors being caused by not following one of them. Are you returning the jQuery object?

Other than that, you really need to post the source of your anims plugin so we can try to see what might be wrong.

OverloadUT
+1  A: 

I solved my problem. Inside my plugin, I wrote:

img = $(this);

and then used the img variable to control everything thereafter. Changing it to:

var img = $(this);

solved my problems. Silly mistake.

Jackie
Use JSLint (www.jslint.com) to check your code, it'll warn for that kind of thing. (Put $ and jQuery into global and check Assume a browser.)
svinto
A: 

You might also find this article that explains common javascript problem when some action is only aplied to the last element of the selection / array or you get the last ID/attribute of your selection.

Uzbekjon