getXPosition

Category:UI Controls

Gets the element's x position.

Since the UI elements in your app are not static but can be moved, your app may need to know where a UI element currently is placed on the screen. All UI elements (button(), textInput(), textLabel(), dropdown(), checkbox(), radioButton(), image()), can be queried for their current position.

Examples

// add the Code.org logo at a random position on the screen and display it's position.
image("logo", "http://code.org/images/logo.png");
setPosition("logo", randomNumber(0,320), randomNumber(0,450));
write(getXPosition("logo"));

Am I off the screen?

Check whether the logo has been displayed too close to the right edge.

// Check whether the logo has been displayed too close to the right edge.
image("logo", "http://code.org/images/logo.png");
setPosition("logo", randomNumber(0,320), randomNumber(0,450));
if (isCloseToEdge()){
  write("Too Close to Edge");
}
function isCloseToEdge(){
  if (getXPosition("logo")>=270) {
    return true;
  } else{
    return false;
  }
}

Syntax

getXPosition(id);

Parameters

Name Type Required? Description
id string The ID of the UI element to find the x position. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _.

Returns

Returns a number representing the current x coordinate in pixels of the UI element within the app display.

Tips

  • The screen default size is 320 pixels wide and 450 pixels high, but you can move a UI element off the screen by exceeding those dimensions.
  • A UI element can be moved off the screen so getXPosition() can return a negative number if the element is off the screen to the left and getXPosition() can return a number greater than 320 if the element is off the screen to the right.

Found a bug in the documentation? Let us know at documentation@code.org