Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a variable from one .js file to another .js?

I have a Symfony application with a menu that creates lashes and use a .js file to load into a div the ulr pointed to each menu option using the load () method. This .js is a variable that acts counter to reference each created tab. This idea can be seen in this example:

http://jsfiddle.net/JMMS_85/o7610t24/

$("#tabs-"+tabCounter).load($(this).attr('href'));

The URL that is loaded into the div has other links, so I created another .js file to block the original link to "preventDefault ()" and I have to reload these links in it earlier div, that is display the url of the new link in the same div, so I have to use the variable counter another .js file on it to know what is the actual div selected.

file1.js

 $(document).ready(function () {
$("#tabs").tabs();
   var tabCounter = 1;
   var cont =1;

        //Code creating the tabs omitted
 $(".container div a").on("click",function(event) {
    event.preventDefault(); 

        tabTitle = $(this).attr("title"),
        addTab();
        $("#tabs-"+tabCounter).load($(this).attr('href'));
        tabCounter++;
        $("#tabs").tabs({active: $('.ui-tabs-nav li:last').index()});
  });
 });

file2.js

$(document).ready(function () {

       $("a").click( function(event)
        {
        event.preventDefault();            

        $("#tabs-"+tabCounter).load(this.href);
    }); 

My problem is how to use the counter variable first .js file to another file.

like image 964
Joseph Avatar asked Apr 16 '15 21:04

Joseph


People also ask

Can I import a variable from another JavaScript file?

To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file. js' .

How is variable accessed from another file?

The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .


2 Answers

You can create the variable outside of functions.

Here you can see how JavaScript Scope works: http://www.w3schools.com/js/js_scope.asp

like image 57
Daniel Moreira Avatar answered Sep 28 '22 08:09

Daniel Moreira


You can also save the variable in the DOM using jquery data

For example:

Setting the initial value

$('#tabs').data('counter', 1);

Retrieving the value

var tabCounter = $('#tabs').data('counter');

Incrementing the value

var tabCounter = $('#tabs').data('counter');
$('#tabs').data('counter', ++tabCounter);

Demo

http://jsfiddle.net/o7610t24/3/

like image 23
Vic Avatar answered Sep 28 '22 08:09

Vic