deleteElement

Category:UI Controls

Deletes the element with the provided id.

The user interface elements you place on the screen on not static. Sometimes you will no longer need an element in your app and it makes more sense to delete it than just hide it. All UI elements (button(), textInput(), textLabel(), dropDown(), checkBox(), radioButton(), image()), can be deleted.

Examples

Squash the ant swarm!

Ants will randomly appear on the screen every second for one minute. Click on the ant to squash it and remove it from the screen.

// Ants will randomly appear on the screen every second for one minute. Click on the ant to squash it and remove it from the screen.
function createAnt() {
  var antId = "ant" + randomNumber(0, 1000);
  var antHeight = randomNumber(35,100);
  var antWidth = randomNumber(35, 100);
  var antXPosition = randomNumber(0, 300);
  var antYPosition = randomNumber(0, 400);
  image(antId, "http://www.pdclipart.org/albums/Animals_Bugs_Insects/ant.png");
  setPosition(antId, antXPosition, antYPosition, antHeight, antWidth);
  onEvent(antId, "click", function() {
    deleteElement(antId);
  });
}

var oneSecondInMilliseconds = 1000;
var oneMinuteInMilliseconds = 60 * oneSecondInMilliseconds;
var createAntInterval = setInterval(createAnt, oneSecondInMilliseconds);

setTimeout(function() {
  clearInterval(createAntInterval);
}, oneMinuteInMilliseconds);

image("ant", "http://www.pdclipart.org/albums/Animals_Bugs_Insects/ant.png");
onEvent("ant", "click", function() {
  deleteElement("ant");
});

Syntax

deleteElement(id);

Parameters

Name Type Required? Description
id string The ID of the UI element to which this event handler applies. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _.

Tips

  • Once you delete an element you can no longer call any functions that reference the element ID until you re-create the element.

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