setImageURL

Category:UI Controls

Sets the URL for the specified image element id.

The images in apps are not always static, they sometimes change based on user or other events. setImageURL() can be used to update the image displayed for an image element ID. There are two ways to fill in the url string for the second parameter.

1. Copy the URL of an image on the web. In most browsers you can simply right-click (ctrl+click on a Mac) on an image and you'll see a menu with a few option. One will be to copy the URL of the image. You could also choose to view the image in its own window and just copy the URL from there.

2. Upload your own image to App Lab. You can upload images saved on your computer to your app in App Lab.

  • Click the pulldown arrow in the image URL field and then click "Choose..."

  • Then click the "Upload File" button the in the window.

  • Then choose the file from your computer by navigating to it

  • Once its uploaded click "Choose" next to it. This will insert the name of the file into the URL field. Because you have uploaded it, it doesn't need to be an HTTP reference.

Examples

// Change the image element from the Code.org logo to the dog character.
image("image", "http://code.org/images/logo.png");
setImageURL("image", "http://studio.code.org/blockly/media/skins/applab/static_avatar.png");

Example: Image Swap

Click the button to change the character image from the dog to the bee and back again.

// Click the button to change the character image from the dog to the bee and back again.
var imageId = "character";
var dogImageURL = "http://studio.code.org/blockly/media/skins/applab/static_avatar.png";
var beeImageURL = "http://studio.code.org/blockly/media/skins/bee/static_avatar.png";
image(imageId, dogImageURL);
var currentImage="dog";
button("changeButton", "Change Character");
onEvent("changeButton", "click", function(event) {
  if (currentImage == "dog") {
    setImageURL(imageId, beeImageURL);
    currentImage="bee";
  } else {
    setImageURL(imageId, dogImageURL);
    currentImage="dog";
  }
});

Syntax

setImageURL(id, url);

Parameters

Name Type Required? Description
url string The source URL of the image to be displayed on screen.
id string The unique identifier for the screen element. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _.

Returns

Modifies screen and returns boolean true if the URL assignment was successful, else returns boolean false.

Tips

  • Image URL requires the full http:// prefix.
  • Use hideElement() to hide an image on the screen.

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