Question

I need to make if parameters optional. If that makes sense.

If you notice both of my functions are 98% the same, I need to turn this difference into a parameter and it's just not clicking for me.

getElement(x, y, class)

where the new parameter class changes what I have marked as //HERE in my code

//get the element under the mouse, ignoring all transparency.
function getElement(x, y){
  var elem = document.elementFromPoint(x, y);
  if($(elem).parents("#game").length != 1){ return -1; }
  var pixelAlpha = mousePixelOpacity(elem, x, y);
  var track = Array;
  for(var i = 0;i<50;i++){
    if($(elem).attr("id") == "game"){ return -1;}
    if(pixelAlpha == 0){ /////////////////////////////////////////HERE
      track[i] = elem;
      for(var z = 0; z<i+1; z++){ //hide elements
        $(track[z]).hide();
      }
      elem = document.elementFromPoint(x, y); //set the element right under the mouse.
      pixelAlpha = mousePixelOpacity(elem, x, y);
      for(var z = 0; z<i+1; z++){ //show all the recently hidden elements
        $(track[z]).show();
      }
    }
    if(pixelAlpha != 0){ ///////////////////////////////////////// AND HERE
      return elem;
    }
  }
  return -1;
}

//get the tile under the mouse, even if it's behind an object
function getTile(x, y){
  var elem = document.elementFromPoint(x, y);
  if($(elem).parents("#game").length != 1 && $(elem).attr("id") != "tileHighlight"){ return -1; }
  var pixelAlpha = mousePixelOpacity(elem, x, y);
  var track = Array;
  for(var i = 0;i<50;i++){
    if($(elem).attr("id") == "game"){ return -1;}
    if(pixelAlpha == 0 || $(elem).attr('class') != "tile"){ /////////HERE
      track[i] = elem;
      for(var z = 0; z<i+1; z++){ //hide elements
        $(track[z]).hide();
      }
      elem = document.elementFromPoint(x, y); //set the element right under the mouse.
      pixelAlpha = mousePixelOpacity(elem, x, y);
      for(var z = 0; z<i+1; z++){ //show all the recently hidden elements
        $(track[z]).show();
      }
    }
    if($(elem).attr('class') == "tile" && pixelAlpha != 0){ ///// AND HERE
      return elem;
    }
  }
  return -1;
}

I was thinking something like

getElement(x, y, "title");

//(This can be right) OR (both of these can be right.)

if( (pixelAlpha == 0) || (class="tile"  &&  onlycountclassifIsaidsovar) ){}

By the way I'm at http://untitled.servegame.com if you want to see this puppy in action.

Thanks!

Was it helpful?

Solution

The only difference I see are three extra tests in getTile(). You could use a boolean third arg (eg, 'tile') which if set would apply those tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top