Search code examples
javascriptenyo

ENYOJS: Set focus on default element on page render


Moonstone Spotlight.

How do I set focus to an element (button etc) after render ?

I've tried nameOfElement.focus() and that does not seem to work.

   rendered : function(){
      this.inherited(arguments);
      var buttonreference = this.$.iconbackbuttonmaster;
      buttonreference.focus();
    }

Here is a >>>> fiddle


Solution

  • Programmatically forcing a Spotlight focus of a Moonstone element requires exercising caution as the general behavior dictates that when in pointer mode, only items hovered by the pointer should be focused, otherwise you end up with the scenario where you can have multiple controls on the screen with Spotlight focus. If necessary, you can usually get around this built-in logic by explicitly disabling pointer mode, but this should force you to pause and reconsider why you are programmatically spotting in the first place. Here is an example that should accomplish what you want (http://jsfiddle.net/aarontam/uam83z55/5/):

    enyo.create({
        components: [
            {name: 'myButton', kind: 'moon.Button', content: 'button to focus'}
        ],
        rendered: function(){
            this.inherited(arguments);
            enyo.Spotlight.setPointerMode(false);
            enyo.Spotlight.spot(this.$.myButton);
        }
    }).renderInto(document.body);
    

    Alternatively, you could add the spotlight class to your control, though the onus would be on the developer to manage removal of the class as appropriate (http://jsfiddle.net/aarontam/uam83z55/6/):

    enyo.create({
        components: [
            {name: 'myButton', kind: 'moon.Button', content: 'button to focus', classes: 'spotlight'}
        ]
    }).renderInto(document.body);