0

I have a map element that has multiple areas, and user can select one of those. Each area has an ID that represents a number (which I need to use in an equation later on).

How do I store the ID of selected area in a variable for later use?

My work so far:

function areaSelection(){
$("map").on('click', 'area', function (e){
    e.preventDefault();
    var areaSelect = parseInt(this.id);


console.log(areaSelect);
});

}

var mapSelection = areaSelection();

$("area").on('click', areaSelection);
Huy Tran
  • 815
  • 1
  • 12
  • 22
user2391365
  • 31
  • 1
  • 6
  • 1
    Create the variable outside of the `areaSelection` function. See **'function scope'** (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions). – evolutionxbox Apr 06 '16 at 23:42
  • Why not the areaSelect variable is a global variable? – Luis Deras Apr 06 '16 at 23:43
  • How about a `variable`? – John Apr 06 '16 at 23:43
  • 1
    Never use global variables. Firstly, you're assigning a function call to a variable, which is returning `undefined`. Secondly, the `areaSelection` function only creates the click event. It doesn't actually calculate the `areaSelect` value. – evolutionxbox Apr 06 '16 at 23:51

1 Answers1

2

Do your best to never use global variables.

Firstly, you're assigning a function call to a variable, which is returning undefined (all functions do this unless the return statement is used).

Secondly, the areaSelection function only creates the click event. It doesn't actually calculate the areaSelect value.


Instead try something like this:

var mapSelection;

$("map").on('click', 'area', areaSelection);

function areaSelection(e) {
    e.preventDefault();
    mapSelection = parseInt(this.id);
}

This way, the mapSelection is getting set any time the map is clicked, but be aware that this is not likely to be efficient.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
  • Bonus points for you! This did the trick! May I ask, why is it inefficient? – user2391365 Apr 07 '16 at 00:07
  • Not sure... there may be something you're calculating on click. The code I provided is not likely to be that inefficient. _(I was trying to cover my butt if someone found a massive issue with the code)_ – evolutionxbox Apr 07 '16 at 00:09
  • @4castle - in personal projects where all code is written by you? none. Otherwise: http://stackoverflow.com/a/2613647/989920 – evolutionxbox Apr 07 '16 at 00:20
  • 1
    @4castle - In little toy projects where all code is written by you globals _might_ be ok. Little. Toy. Projects. In anything of _any_ significant size global variables will likely lead to unintended side-effects as various bits of code read and write values on the global, even if you are the only coder. Encapsulation is key; code should be unaffected by things outside that code. Discussion of this is everywhere, in books, tutorials, web articles, etc.; it is an extremely basic concept in program design. – Stephen P Apr 07 '16 at 00:42