zealisreal
zealisreal

Reputation: 505

Passing a variable specifically from one function to another in jquery without making it global

I am looking for some help in a jquery script I am in the process of creating, ill try and break it down in plain english.

The script works off the back of a grid utilised via a <ul></ul> element, each <li></li> forms the individual component of the grid.

If you hover over a list-item the jquery script will then expand that element to take up the entire dimensions of its parent through an animation. It stays there until the cursor is moved off and should resize itself back to its original position and it is there which I am having my problem (it seems the variable from the expand function is not passing properly into the shrink function).

Hopefully that helps give a brief understanding, if not please view the jsfiddle example

http://jsfiddle.net/EzYeH/3/

Thank you in advance anyone who could decode my ramblings and help.

Dan.

Upvotes: 0

Views: 383

Answers (2)

jfriend00
jfriend00

Reputation: 707326

To start with, you aren't implementing the callback functions expand() and collapse() properly. Per the hoverIntent plugin doc, the arguments to those functions are the same as mouseover which means there's one argument and it's the event object and this is set to your object. That means it isn't working because leftPos and topPos are not the arguments to those functions. To make this work, you will need to compute the desired leftPos and topPos in the function - they won't be passed to it.

If you need to store the original position somewhere other than a global variable (something I'm not sure you actually need to do), you can store it on the animating object itself using jQuery's .data() method.

To help you with a new version of the code, I'd need to understand where you expect the animation of a given object to go to/from each time. I don't follow exactly what you want the starting/ending points to be so I'm not sure what code to recommend that calculates it properly.

Upvotes: 1

David Brainer
David Brainer

Reputation: 6331

I believe that I understood what you were trying to do, and here is one possible solution: http://jsfiddle.net/EzYeH/4/

To answer your fundamental question, one way to "pass" data from your starting function to your ending function is to store it as data- on the element itself:

$this = $(this);
var position = $this.position();
$this.data('leftPos', position.left + 'px');
$this.data('topPos', position.top + 'px');

Upvotes: 1

Related Questions