views:

199

answers:

2

Hi,

I have the following jQuery code. As you can see, I have an alert that display the current tab that I am on based on the value from this.getIndex().

My question is, how can I get access to this value, so that I can use it within other javascript functions that don't reside with the ready(function)?

I want to be able to say instead:

tabIndx = this.getIndex() and when this value changes, I want to use it within another function down below, outside of the ready(function), say

var tabIndx;

$(document).ready(function(){ 

    // initialize scrollable 
    $("div.scrollable").scrollable({
     size: 1,
     items: '#thumbs',  
     hoverClass: 'hover',
                onSeek: function() {
                  alert("Current tab is: "+ this.getIndex()); 
                }
    });
});


function showVal() {
  alert("current tab selected is: "+ tabIndx);
}

So everytime I click on different tabs, I want the showVal() function to fire with the correct value for tabIndx.

Any ideas.

Thanks. Tony.

+2  A: 

Replace this:

alert("Current tab is: "+ this.getIndex());

With this:

tabIndx = this.getIndex();
showVal();

That's all there is to it. There's nothing special about the $(document).ready() function. It's just an ordinary JavaScript function that happens to come with jQuery, and that jQuery happens to call when the document is ready.

You can freely call other functions, and access variables declared outside the $(document).ready() just as you can with any JavaScript function.

VoteyDisciple
Thanks for the quick response Votey - let's say that I actually also wanted to pass this tabInx value into a javascript function parameter - would I need to call this function with parameter from within the onSeek function?
tonsils
You can use tabIndx in any way you like as long as it's in scope. As you've declared it there, it's global, so you can refer to tabIndx (including passing it as an argument) from ANYWHERE in your script. Keep in mind, of course, that although the variable is in scope, it won't have a meaningful value until the onSeek event fires, so using it within that function is probably wise.
VoteyDisciple
A: 

You've declared your tabIndx to be global, so that should suffice for your needs. I would initialise it as well:

var tabIndx = 0;

The way you are using this within your jQuery will refer back to the div in your selector (div.scrollable), so using it in conjunction with your getIndex() function is a bit meaningless.

Referring to tabIndx wether for getting the value or setting should be just fine.

Unless I've completely misunderstood what you want...

James Wiseman