Gert Cuykens
Gert Cuykens

Reputation: 7155

Can't get my input focus to work?

Why does my this.$.search.focus() not work?

<polymer-element name="site-search">
  <template>

<style>
  :host {
	font-family: 'RobotoDraft', sans-serif;
	font-size: 14px;
  }
  .condensed  input, .condensed /deep/ .underline {
    display: none;
  }
</style>

<section horizontal layout>
    <core-icon-button
      id="button"
      icon="search"
      title="search"
      aria-label="search"
      disabled?="{{!canBeCondensed}}"
      on-tap="{{toggleSearch}}">
    </core-icon-button>
	
    <paper-input-decorator flex
      label="{{label}}"
      floatingLabel="{{floatingLabel}}"
      value="{{value}}"
      disabled?="{{disabled || condensed}}"
      class="{{ {condensed: condensed} | tokenList }}">
        <input
          id="search"
          on-blur="{{onBlur}}"
          type="search"
          value="{{value}}"
          committedValue="{{committedValue}}"
          on-keyup="{{onKeyUp}}"
          disabled?="{{disabled}}">
    </paper-input-decorator>
</section>

  </template>

  <script>
Polymer({
  publish: {
    label: '',
    floatingLabel: false,
    disabled: {value: false, reflect: true},
    canBeCondensed: false,
    condensed: false,
    site: window.location.hostname
  },
  toggleSearch: function() {
    if (!this.canBeCondensed) return;
	this.$.search.focus()  <==== Doesn't work. Why?
    this.condensed = !this.condensed;
	this.$.button.hidden=true
  },
  onKeyUp: function(e) {
    if (e.keyCode == 13) {  // Enter.
      var q = encodeURIComponent('site:' + this.site + ' ' + this.value);
      window.open('https://www.google.com/search?q=' + q);
    }
  },
  onBlur:function(e) {
	this.condensed = !this.condensed;
    this.$.button.hidden=false
  },
});
  </script>

</polymer-element>

Upvotes: 2

Views: 841

Answers (1)

Justin XL
Justin XL

Reputation: 39006

Try removing .condensed input, in your css.

Because when you change the class of the paper-input-decorator, your original css will update the inner input's class too, and this will cause the input to lose focus.

Alternatively, you can remove the whole class="{{ {condensed: condensed} | tokenList }}" and hide/show the underline element in js. For example -

toggleSearch: function () {
    if (!this.canBeCondensed) return;
    this.$.search.focus();
    //this.condensed = !this.condensed;
    this.$.button.hidden = true;

    var underline = document.querySelector('paper-input-decorator::shadow .underline');
    underline.hidden = true;
},

Upvotes: 2

Related Questions