pixo-drone
pixo-drone

Reputation: 83

Returning a variable to use within another function in JQuery

I'm making an image gallery, when I click a button I can scroll through to the next image.

I also have the option to 'jump' to a specific image. This all works fine.

However, if I scroll regularly to image 3, then jump to image 7. Once I click the next button, I don't go to image 8 as I would like to - I go to image 4. Because there are two separate functions, and I can't/ don't know how to pass the variable between them. I understand I can use a global variable outside of both functions, but this seems to be discouraged.

Here's an example:

var i = 0;
// i is a global variable

$("#next_button").click(function(){
   $(".all_images").eq(i).show();
   i++;
});

This would correctly increment through all of my images.

$(".thumbnails").click(function(){
    var x = $(this).index();
    $(".all_images:visible").hide();
    $(".all_images").eq(x).show();

i = x;
});

This shows the image relative to the thumbnail I have clicked.

So, how do I use the 'i' variable from the first function in the second function? This has always confused me. It just seems simpler to use a global variable so each function can change the value of i and use it when necessary. Please enlighten me.

Also, as I understand it's possible to wrap JQuery code in a regular JavaScript functions. It seems, however, that my code doesn't work when I wrap a JQuery .click in a regular JavaScript function (ie my_Function(){ ....$("#something").click.... }

Can anybody explain what I am doing wrong?

Upvotes: 0

Views: 1426

Answers (1)

Menelaos
Menelaos

Reputation: 26279

You have two options as in most programming languages:

  1. Use a global variable (higher scope),
  2. Pass by reference.

However, you can't really escaoe creating some kind of global variable (object or primitive) so I would suggest you make an object (maybe even key-value) that holdes all your program parameters.

In order to do this you could use the .data method like this to assign data to an arbitrary element:

setter : 
$('body').data('myvar','value');

getter:
$('body').data('myvar');

see: http://api.jquery.com/jQuery.data/

In order to pass by reference, you need to pass a object instead of a primitive. See following link(s) for more details:

Upvotes: 1

Related Questions