How to access variable inside jquery from regular javascript function

I am new to jquery. I am trying to access a variable defined inside a jquery block outside of jQuery (from a regular function) like this, but I cannot access it. Can anyone tell me how?

<script language="javascript"> $(function() { ....... ....... ....... var api = pane.data('jsp'); var current_location = api.getContentPositionX(); } function change_title(t_index) { alert("print="+$.current_location); window.location.href="page.php?p="+$.current_location); } 

I want to get the value for $ .current_location.

Thanks.

+4
source share
4 answers

There is no such thing as a jQuery variable, they are all regular Javascript variables.

The reason you cannot access the current_location variable from your function is because the variable is declared locally inside another function.

Just declare the variable outside the functions so that it is global, and you can access it from both functions:

 var current_location; $(function() { ....... ....... ....... var api = pane.data('jsp'); current_location = api.getContentPositionX(); } function change_title(t_index) { alert("print=" + current_location); window.location.href = "page.php?p=" + current_location; } 
+7
source

The jQuery object is global, unless of course you include jQuery in the page. Therefore, calling $ .property or jQuery.property ($ is alias) should work as long as the property exists, is set, and is publicly available.

You might want to make current_location var be a member of the jQuery object:

 $(function() { ....... ....... ....... var api = pane.data('jsp'); this.current_location = api.getContentPositionX(); } 
0
source

you need to save current_location on a globally accessible object. either window , or a custom object that you use as an object with a namespace.

 <script language="javascript"> var current_location = null; var obj = {}; $(function() { ....... ....... ....... var api = pane.data('jsp'); current_location = api.getContentPositionX(); obj.current_location = current_location; }) function change_title(t_index) { obj.current_location; alert("print="+$.current_location); window.location.href="page.php?p="+current_location); } 
0
source

The variable is defined in the first function, so the scope of this variable is only in the first function and, therefore, cannot be visible from outside this function.

Try defining a variable outside the function so that it has a larger scope.

0
source

All Articles