How to update variable in the JS file from a child aspx page

53 Views Asked by At

I have a JS file with below code. I need to update the value of variable currentIndex from my child aspx page. Right now this js refrence is over a parent page. I would like to know how to do it. What syntax should be passed from child.aspx page to have the updated value of currentIndex everywhere.

(function($, global, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...
1

There are 1 best solutions below

2
On BEST ANSWER

You could expose a function that will modify the currentIndex variable to global scope. But this approach does not scale well and should be considered as bad practice, because it could cause name clashes and other downsides. How to avoid global variables in JavaScript?. So if you need to access parent page from child iframes you should think of better approach like communication through messages https://stackoverflow.com/a/41566923/2138959 or similar custom implementation.

For the time being the easiest way to solve your problem to define a setter function that will update currentIndex variable:

(function($, undefined) {
  var slides, currentIndex, $container, $fragmentLinks;

  window.setCurrentIndex = function(indexValue) {
    currentIndex = indexValue;
  };

  var events = {
...
     prev: function() {
       methods.go(currentIndex-1);
     },
...

And if you want to set index to value 3 for instance you could do:

window.setCurrentIndex(3);