0

I have five possible buttons to push and each of these buttons runs the same function. But I would also like that button push to make a unique global variable too. A variable that says "this button was pushed so add this "word" where ever needed.

document.getElementById("One").addEventListener("click", Variables);
document.getElementById("Two").addEventListener("click", Variables);
document.getElementById("Three").addEventListener("click", Variables);
document.getElementById("Four").addEventListener("click", Variables);
document.getElementById("Five").addEventListener("click", Variables);

So they all run exactly the same function but the "One" or "Two" or "Three" string needs to become a global variable. I later use these to make some numbers:

For example I would use "One" to make one of these outcomes:

if (mapNumber = "One" || "Three" || "Four") { 
    climate = ["dry", "light rain", "medium rain", "heavy rain", "light snow", "medium snow", "heavy snow", "light ice", "very icy", "severe ice"];

I am at a bit of a loss on how to call this to make it a global. I tried making a function inside the function but it seemed to cause the other function to stop. So I am guessing I have made a syntax error somewhere.

I tried doing an onclick="myFunction(this.id)" function as well as the EventListener but this didn't seem to work either.

A pointer in the right direction would definitely be helpful. I have done searches, but these all seem to produce local variables at best.

Thanks :)

2
  • if (mapNumber = "One" || "Three" || "Four") is wrong on multiple levels Commented Sep 10, 2020 at 20:41
  • 1
    Hi @PaulDavis Were any of the below answers helpful to you? If so, please select a "correct" answer (by clicking the checkmark beside an answer) to close the question, or provide an answer yourself and choose that as the correct answer. Otherwise, please add comments below one of the answers or edit your original question to add more detail so that additional assistance can be provided. That will help us out. (Also remember that upvoting is encouraged in order to reward answers that were particularly informative - and it is possible to also upvote the answer that you checkmark.) Thanks! Commented Sep 13, 2020 at 21:22

2 Answers 2

2

You can do it like this:

  1. Add a container with a class or id for your buttons so we can select them all easily
  2. querySelectorAll to get all buttons and...
  3. ...loop through these using forEach and add your event handler for clicks
// Get all buttons
const mybuttons = document.querySelectorAll('.mybuttons button');

// loop through the buttons and add the event listener to each button
mybuttons.forEach(mybutton => {
   mybutton.addEventListener('click', processClick);
});
  1. Create a global variable mapNumber to save the id of the clicked button
    UPDATE: Note - you need to use var and not let so that is can be accessed using window.variablename
  2. Create a function to handle the click and we can get the id to tell us which button was clicked and use this for mapNumber:
var mapNumber;
function processClick() {
    mapNumber= this.id;  // the id of the clicked button 
}

Working Example:

var mapNumber;  
var climate;

//get all buttons in the mybuttons container
const mybuttons = document.querySelectorAll('.mybuttons button');

// add the event listener to each button
mybuttons.forEach(mybutton => {
     mybutton.addEventListener('click', processClick);
});

function processClick() {
    // save the id of the clicked button as mapNumber
    window.mapNumber = this.id;

    // set climate variable based on which was clicked, e.g.        
    switch(window.mapNumber){
        case "One":
        case "Three":
        case "Four":
            climate = ["dry", "light rain", "medium rain", "heavy rain", "light snow", "medium snow", "heavy snow", "light ice", "very icy", "severe ice"];
            break;
        case "Two":  climate = ["Two's climate"]; break;
        case "Five": climate = ["Five's climate"]; break;
    }

    // Display the mapNumber, just to show its working :)
    document.getElementById('mapNumber').innerHTML = "mapNumber: "+window.mapNumber;
    document.getElementById('climate').innerHTML = "Climate: "+climate;
}
<div class="mybuttons">
  <button id="One">One</button>
  <button id="Two">Two</button>
  <button id="Three">Three</button>
  <button id="Four">Four</button>
  <button id="Five">Five</button>
</div>
<div id="mapNumber">mapNumber:</div>
<div id="climate">Climate:</div>

Sign up to request clarification or add additional context in comments.

11 Comments

This is awesome and will work. But the only global variable I need from this is "One" or "Two" or "Three" etc. Climate is already a global but the outcome needs to be filled in based on which map button was clicked. Then that same "One" or "Two or "Three etc is then parsed into several other variables based on that button click.
@PaulDavis Then just set the global variable to the id :) I'll edit my answer
;) Perfect... I just don't know how to do that. So... const mybuttons = document.querySelectorAll('.mybuttons button'); That's cool, I can use that to scan all buttons. Then this listens for a button push: mybuttons.forEach(mybutton => { mybutton.addEventListener('click', processClick); }); No problems for me so far... It's the next thing. I want mapNumber = [what ever button was pushed, eg "One" or "Two"] and that has to be global.
It's just that last bit I am struggling with, how do I get that mapNumber = {some button push} to be global?
let mapNumber; function processClick() { mapNumber = this.id; console.log("Map number is", mapNumber); What ever I am doing it is blocking the rest of the function. So for me, it is about placement, I don't know where to place this to make mapNumber global easily. I would like to use window.mapNumber or something, but I do not know how.
|
1

You can make something a global by putting window. in front of it.

Example:

function notInGlobalScope() {
  window.str = "I'm in global scope!";
}
notInGlobalScope();
console.log(str);

In your example:

function Variables() {
    if (this.id = "One" || "Three" || "Four") { 
    window.climate = ["dry", "light rain", "medium rain", "heavy rain", "light snow", "medium snow", "heavy snow", "light ice", "very icy", "severe ice"];
    }
}

document.getElementById("One").addEventListener("click", Variables);
document.getElementById("Two").addEventListener("click", Variables);
document.getElementById("Three").addEventListener("click", Variables);


document.body.onclick = ()=>{
    if(window.climate) {
        console.log(climate);
    }
}
body {
    min-height:30vh;
}
<button id="One">1</button>
<button id="Two">2</button>
<button id="Three">3</button>
<p>Click anywhere to get value of climate</p>

3 Comments

ok, that seems like a reasonable option. I might have a go at using the onclick method then to see if that works.
@PaulDavis I updated the answer to include something more relevant to what you provided.
I am trying the first method, it is probably the best. Except I don't really know the syntax. function mapNum (clicked) { Then what? How do I get mapNumber = [map number clicked] (eg "One" or "Two" depending on the ID of the map)? and then make that glboal=

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.