How to get a global variable out of a eventListener function

I have a form field with an input. This function takes the input value and open another site.
index.js

// take pattern number from input
let go = document.querySelector('#goBtn');
go.addEventListener('click', patternNumber);

var pNum;
function patternNumber(){
    pNum = document.querySelector('#pattrnNum').value;
    if (pNum > 86){
        alert("The pattern " + pNum + " is not available");
    }else{
        window.location = '0' + pNum + '.html';
    }
}

I declared the var outside the function and assigned inside. The function by them self is working and calls he new site. But when try to call the same var pNum in another script, it says: Uncaught ReferenceError: pNum is not defined
I have both js scripts referenced at the end of the html scripts.
Why can I not use the declared global variable in different scripts?

ok, here the full code:

  1. index.html
<!--input section-->
<section id="form">
    <div class="container text-center mt-3">
        <div class="row">
            <div class="col"></div>
            <form id="forPattern">
                <div class="form-group col">
                    <label for="pattrnNum">Pattern Number</label>
                    <input type="text" id="pattrnNum" class="form-control d-inline" name="pattrnNum" placeholder="Pattern Number">
                    <small class="form-text text-muted">Please type in, the number for the pattern you want to see</small>
                    <button id="goBtn" onclick="patternFunction()" class="mt-3 btn btn-outline-warning btn-sm" type="button">See The Pattern</button>
                </div>
            </form>
        </div>
    </div>
</section>


<script src="js/index.js"></script>
<script src="js/pattern.js"></script>

next part is the pattern.html
with that part where 5the number (here 050) to replace with the var pNum by using .createElement

<div id="arena" class="container text-center">
            <img id="pic" src="img/050/050pattern.png" alt="Pattern 50">
</div>

as well as using the pNum with the button

<button type="button" class="btn btn-outline-info btn-sm" id="btn1">Pattern Setup</button>

to call an img with the
pattern.js

let start = document.querySelector('#btn1');
start.addEventListener('click', function(){
    let img = document.querySelector('#pic');
    img.src = "img/0" + pNum + "/0" + pNum + "pattern.png";
});

Thank you!

3 Likes

Google cross-site-scripting for more insight.

That should not be a problem on the same page since all JS shares the same namespace for a given document. Crossing into another namespace seems a bit far-fetched. There would be the need of an intermediary to bridge the gap. Query strings comes to mind.

3 Likes

You’ve only shown a third of your code (can’t reproduce)

2 Likes

yes, i will try the query string… Thanks
it seams a global var isn’t so global. Or is there a way to import a function in JS and than use the dot notation (like in python for example)?

2 Likes

You’re doing a lot more than just that, you can quickly show that they are global by doing that and only that

2 Likes

Hmmm… ok. I would really appreciate it if you can show me (point me in the right direction) how to handle it in JavaScript. I was ‘battling’ with that topic now for over a week and could not figure it out. What I’m looking for is how I can use a var or a result/ return of a function from script1.js in script2.js in combination with html (DOM). I’m relatively new to JS and probably thinking to much in the way like Python is, what I’m pretty familiar with. Thank you!!

2 Likes

In terms of global variables there’s no issue there

<script>a = 4</script>
<script>console.log(a)  // writes 4 to console</script>

So what’s really going on is probably that one of your assumptions aren’t holding up (you’re testing a lot of things all at once, and then deciding which is responsible, but it could be other things. need to test these things in isolation from each other)

For all I know, you do this:

<script>console.log(a)  // a doesn't exist</script>
<script>a = 4</script>

I don’t know what the problem is. If a bug can’t be reproduced then it doesn’t exist, right?

2 Likes

…understand, I will check the order and than isolate ever single step.
I did assume that I can import a script like a module and use dot notation to use ta function from another script. That was whatI was searching, but couldn’t find. I need to rethink and start over in small steps like you said

2 Likes

I know very little of how things are done on the web, I mostly assume it’s a bunch of ugly hacks that I don’t want to know anything about.

You can certainly emulate modules. One way to go about it is to have each module be a function which returns an object with exports (I believe this is what nodejs does)

You could then either have a central import system so that each module is imported only once with guarantees of no cycles and all such things, or call the modules to obtain an instance of their exports. Doing that yourself would work in small scale, but so would global variables so it’s not exactly solving that problem, it will in particular not solve your bug because we already established that global variables are accessible between scripts. I imagine there exists libraries for doing this.

function module1() {
  function f(){}
  function g(){exports.x = 7}
  ...
  let exports = {f, g}
  return exports
}
4 Likes

Thank you, I will that way, but definitely start with breaking it down and isolate.

3 Likes