Search code examples
javascriptjqueryarraysmouseclick-event

Code Advice - How to make more concise (Javascript/Jquery)


I'm trying to make my code more concise (i.e., less repeated code). I've gotten some advice from my supervisor as to how to make my recent code more concise, but I'm not exactly sure how to do it.

I have some coordinates that I am using to check if the user clicks within a certain area of a div. I was told that I should put all the coordinates in an array and "loop through" to get them when I need them. I -think- I understand what he was suggesting, but I can't quite wrap my head around it since I'm still inexperienced with programming. Here's what I have done so far so you can get a better idea of what's going on:

    $("#div1").click(function(e)
    {
        // Arrays containing the x and y values of the rectangular area around a farm
        // [minX, maxX, minY, maxY]
        var div1_Coord_Area1= [565, 747, 310, 423];
        var div1_Coord_Area2= [755, 947, 601, 715];

        if(areaX >= Reg2_Coord_Farm1[0] && areaX <= Reg2_Coord_Farm1[1] && areaY >= Reg2_Coord_Farm1[2] && areaY <= Reg2_Coord_Farm1[3]) 
        {
            alert("You clicked in the first area");
        }
        if(areaX >= Reg2_Coord_Farm2[0] && areaX <= Reg2_Coord_Farm2[1] && areaY >= Reg2_Coord_Farm2[2] && areaY <= Reg2_Coord_Farm2[3]) 
        {
            alert("You clicked in the second area");
        } 
});

Do not worry about how I do the calculations; I left that code out of the method since it is basically irrelevant, but it is there in case you were wondering.

I made an array for each set of coordinates and simply call those. This isn't "looping through" a giant array filled with all of the coordinates of each area, however. Can you conceive of a way of doing this, or is the best I could do at the moment?


Solution

  • I think what he means is something more like this:

    $("#div1").click(function(e){
        // Arrays containing the x and y values of the rectangular area around a farm
        // For each array: [area1, area2, area3, ... areaX]
        var minX = [565, 755];
        var maxX = [747, 947];
        var minY = [310, 601];
        var maxY = [423, 715];
    
        for (var i = 0; i < minX.length; i++) {
          if (areaX >= minX[i] && areaX <= maxX[i] && areaY >= minY[i] && areaY <= maxY[i]) {
            alert("You clicked in area " + (i+1));
          }
        }
    });
    

    This way, you can have many more areas to check but never have to change the loop as it will always iterate through all items in the array, be it 2 like above, or 10, or 100.