How to get first element of parent object

You must Login before you can answer or comment on any questions.

Hi,

Perhaps a stupid question but I am new to Titanium mobile and ran into a "problem". I have a button, which contains an image. When the button is clicked I want the image to change.

How could I check in the event listener what image is clicked and then change it's image?

Some code:

var btnAvailability = Titanium.UI.createButton({
   title: 'Hello',
   width: "25%",
   height: "100%",
   left: 0,
});
 
var imgAvailability = Titanium.UI.createImageView({
    image: "./images/availability_btn.png"
});
 
btnAvailability.add(imgAvailability);

— asked 2 years ago by vincent c
0 Comments

1 Answer

Accepted Answer

Hi

There are two ways;

  • in the button event listener access the source property of the event return object - that will be the actual thing clicked as the event bubble up.

    btnAvailability.addEventListener('click', function (e) {
        e.source.setImage('somethingelse.png')
    });
    To make this safer add a custom property to your images so you can tell they are things you can play with;
    var imgAvailability = Titanium.UI.createImageView({
        isImage: true, // can be ANY name you like as long as the property does not already exist
        image: "./images/availability_btn.png"
    });
    btnAvailability.addEventListener('click', function (e) {
        if (e.source.isImage === true) {
            e.source.setImage('somethingelse.png')
        }
    });
    This way it only occurs if the item clicked is an actual image (or anything you want to look out for). This is because source is a reference to the original item.

  • add an event to the image itself

    imgAvailability.addEventListener('click', function (e) {
        imgAvailability.setImage('somethingelse.png')
    });
    Simple - once you know how, and now you do :)

— answered 2 years ago by Malcolm Hollingsworth
answer permalink
2 Comments
  • Thanks! Indeed, easy once you know it :). Thanks for your time!

    — commented 2 years ago by vincent c

  • I thought it would be working but I keep getting [INFO] [object TiUIButton] returned instead of the image..

    — commented 2 years ago by vincent c

Your Answer

Think you can help? Login to answer this question!