4

I have one test.html file with two <script> tags. I need to share a variable from one to another..

Sample code:

<script type="text/javascript">
  var test = false;

  function testing() {
    test = true;
    alert('I am inside..');
  }

  testing();
</script>
...
<script type="text/javascript">
  if (test == true) {
    alert('working');
  } else {
    alert('failed');
  }
</script>

The output is always:

I am inside..

failed

I also tried to use the window class but it doesn't matter.. (window.test)

What I have to do to get the 'working' alert?

Thanks if anyone can help me. I saw some similar questions, but the answers wasn't a solution for me.

EDIT:

The original code (simplified):

<head>
    ...
    <script type="text/javascript" src="detectblocker.js"></script>
    <!-- GitHub: https://github.com/sitexw/BlockAdBlock/ -->
    ...
</head>
<body>
    <script type="text/javascript">
        var blocker = false;

        function adBlockDetected() {
            blocker = true;
            alert('inside');
        }

        if(typeof blockAdBlock === 'undefined') {
            adBlockDetected();
        } else {
            blockAdBlock.onDetected(adBlockDetected);
        }

        blockAdBlock.setOption({
            checkOnLoad: true,
            resetOnEnd: true
        });
    </script>
    <div class="header">
        ...
    </div>
    <div class="content_body">
        <div class="requirs">
            <ul>
                ...
                <script type="text/javascript">
                    if (blocker == true) {
                        document.write("<li>enabled!</li>")
                    } else {
                        document.write("<li>disabled!</li>")
                    }
                </script>
                ...
            </ul>
        </div>
    </div>
    ...
</body>

The output is an alert() "inside" and the <li> "disabled".. (Blocker is enabled..). The only difference I can see is on the end of the first <script> tag:

blockAdBlock.setOption({
    checkOnLoad: true,
    resetOnEnd: true
});

So why the snippet is working and my code not? Confusing...

20
  • 1
    I converted your snippet to a live demo and … it works. Whatever the problem is, you haven't exposed it in your question. Commented Dec 2, 2016 at 13:36
  • 1
    @xShirase — The problem never appeared in the first place. The edit just highlights that it never appeared. Commented Dec 2, 2016 at 13:39
  • 1
    i copied that code and tried .That works perfect .where is the issue? Commented Dec 2, 2016 at 13:40
  • 2
    @13loodH4t — After your edit … it still outputs "enabled" so you still don't seem to have provided a minimal reproducible example Commented Dec 2, 2016 at 14:24
  • 1
    If you hit the else branch of if(typeof blockAdBlock === 'undefined') and blockAdBlock.onDetected is asyncronous (which it sounds like it is) then this is a duplicate of this question. Since you haven't provided a minimal reproducible example it isn't possible to tell for sure though. Commented Dec 2, 2016 at 14:27

3 Answers 3

2

If you do not use var before a variable it becomes a global variable like

test = true;

The variable test will be true during the page and also in your next scripts and functions.

Try this:

    <script type="text/javascript">
      var test = false;

      function testing() {
        var test = true;
        alert('I am inside..');
      }

      testing();
    </script>
    ...
    <script type="text/javascript">
      if (test == true) {
        alert('working');
      } else {
        alert('failed');
      }
    </script>
Sign up to request clarification or add additional context in comments.

7 Comments

It's not working.. as var create a new variable scope inside the function.
"if you do not use var before a variable it become's as an global variable" — test needs to be a global variable for it to be read in the second script element!
@alifallahi — I just explained that in my last comment.
test has false value, just inside testing() it becomes true. so near the end because of else the last alert will show failed
@alifallahi — No. test has a false value. Then inside testing you create a different variable, also called test and assign true to that. The function ends and the second test variable goes out of scope. Then the second script reads the original, global, variable (which is still false).
|
1

There are two ways of doing it.
1) create a hidden element and set your variable from your first script to attribute of that element. This is your hidden element

<input type="hidden" id="hiddenVar"/>

and can set it in javascript as

document.getElementById("hiddenVar").setAttribute("myAttr",test)

Now you can get it in next script as

document.getElementById("hiddenVar").getAttribute("myAttr")

2) By .data() you can read about it here

2 Comments

Shoving things in DOM is a massively over complicated approach to this problem. Simply using a variable will work fine … and does in the code provided in the question. Anything that would break the approach the question is using would be likely to break the DOM approach too.
hidden input field looks bad for me and I don't really want to use this.. for 2) .data() I will take a look.. thanks
0

Using window's global variables may be what some are looking to do. You can read more in this answer, or the docs.

<script type="text/javascript">
  window.test = 'some text';
</script>
...
<script type="text/javascript">
  alert(window.test);
</script>
...
<script type="text/babel">
  alert(window.test);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.