tonyf
tonyf

Reputation: 35557

jQuery ready function value passing to JavaScript functions

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 every time I click on different tabs, I want the showVal() function to fire with the correct value for tabIndx.

Upvotes: 0

Views: 1322

Answers (2)

Mutation Person
Mutation Person

Reputation: 30500

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...

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37803

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.

Upvotes: 2

Related Questions