bootstrap-typeahead.js 7.31 KB
Newer Older
Jacob Thornton's avatar
Jacob Thornton committed
1
/* =============================================================
Mark Otto's avatar
Mark Otto committed
2
 * bootstrap-typeahead.js v2.1.1
Jon Stevens's avatar
Jon Stevens committed
3
 * http://twitter.github.com/bootstrap/javascript.html#typeahead
Jacob Thornton's avatar
Jacob Thornton committed
4
 * =============================================================
Mark Otto's avatar
Mark Otto committed
5
 * Copyright 2012 Twitter, Inc.
Jacob Thornton's avatar
Jacob Thornton committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

20

21
!function($){
Jacob Thornton's avatar
Jacob Thornton committed
22

23
  "use strict"; // jshint ;_;
Jacob Thornton's avatar
Jacob Thornton committed
24

25
26
27
28
29

 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
Jacob Thornton's avatar
Jacob Thornton committed
30
31
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
32
33
34
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
35
    this.updater = this.options.updater || this.updater
Jacob Thornton's avatar
Jacob Thornton committed
36
    this.$menu = $(this.options.menu).appendTo('body')
37
    this.source = this.options.source
Jacob Thornton's avatar
Jacob Thornton committed
38
39
40
41
42
43
44
45
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

46
47
  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
48
      this.$element
49
        .val(this.updater(val))
50
        .change()
51
      return this.hide()
Jacob Thornton's avatar
Jacob Thornton committed
52
53
    }

54
55
56
57
  , updater: function (item) {
      return item
    }

Jacob Thornton's avatar
Jacob Thornton committed
58
  , show: function () {
59
      var pos = $.extend({}, this.$element.offset(), {
60
61
62
63
64
65
66
67
        height: this.$element[0].offsetHeight
      })

      this.$menu.css({
        top: pos.top + pos.height
      , left: pos.left
      })

Jacob Thornton's avatar
Jacob Thornton committed
68
      this.$menu.show()
69
      this.shown = true
Jacob Thornton's avatar
Jacob Thornton committed
70
71
72
73
74
      return this
    }

  , hide: function () {
      this.$menu.hide()
75
      this.shown = false
Jacob Thornton's avatar
Jacob Thornton committed
76
77
78
79
      return this
    }

  , lookup: function (event) {
80
      var items
81
82

      this.query = this.$element.val()
83

Jacob Thornton's avatar
Jacob Thornton committed
84
      if (!this.query || this.query.length < this.options.minLength) {
85
86
        return this.shown ? this.hide() : this
      }
Jacob Thornton's avatar
Jacob Thornton committed
87

88
89
90
91
92
93
94
95
96
      items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source

      return items ? this.process(items) : this
    }

  , process: function (items) {
      var that = this

      items = $.grep(items, function (item) {
97
        return that.matcher(item)
Jacob Thornton's avatar
Jacob Thornton committed
98
99
      })

100
101
      items = this.sorter(items)

Jacob Thornton's avatar
Jacob Thornton committed
102
103
104
105
      if (!items.length) {
        return this.shown ? this.hide() : this
      }

106
      return this.render(items.slice(0, this.options.items)).show()
Jacob Thornton's avatar
Jacob Thornton committed
107
108
    }

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
129
      var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
130
      return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
131
132
133
134
        return '<strong>' + match + '</strong>'
      })
    }

135
  , render: function (items) {
Jacob Thornton's avatar
Jacob Thornton committed
136
137
138
      var that = this

      items = $(items).map(function (i, item) {
139
        i = $(that.options.item).attr('data-value', item)
140
        i.find('a').html(that.highlighter(item))
141
        return i[0]
Jacob Thornton's avatar
Jacob Thornton committed
142
143
144
      })

      items.first().addClass('active')
145
      this.$menu.html(items)
Jacob Thornton's avatar
Jacob Thornton committed
146
147
148
149
150
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
151
152
153
154
155
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }
Jacob Thornton's avatar
Jacob Thornton committed
156
157
158
159
160
161

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
162
        , prev = active.prev()
Jacob Thornton's avatar
Jacob Thornton committed
163

164
165
166
167
168
      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
Jacob Thornton's avatar
Jacob Thornton committed
169
170
    }

171
172
173
174
175
176
  , listen: function () {
      this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

177
      if ($.browser.chrome || $.browser.webkit || $.browser.msie) {
178
        this.$element.on('keydown', $.proxy(this.keydown, this))
179
180
181
182
183
184
185
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
    }

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
  , move: function (e) {
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }

      e.stopPropagation()
    }

  , keydown: function (e) {
Jacob Thornton's avatar
Jacob Thornton committed
211
      this.suppressKeyPressRepeat = !~$.inArray(e.keyCode, [40,38,9,13,27])
212
213
214
215
216
217
218
219
      this.move(e)
    }

  , keypress: function (e) {
      if (this.suppressKeyPressRepeat) return
      this.move(e)
    }

220
221
222
223
224
  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
          break
Jacob Thornton's avatar
Jacob Thornton committed
225
226
227

        case 9: // tab
        case 13: // enter
228
          if (!this.shown) return
Jacob Thornton's avatar
Jacob Thornton committed
229
230
231
232
          this.select()
          break

        case 27: // escape
233
          if (!this.shown) return
Jacob Thornton's avatar
Jacob Thornton committed
234
235
236
237
238
239
          this.hide()
          break

        default:
          this.lookup()
      }
240

241
242
      e.stopPropagation()
      e.preventDefault()
Jacob Thornton's avatar
Jacob Thornton committed
243
244
  }

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
  , blur: function (e) {
      var that = this
      setTimeout(function () { that.hide() }, 150)
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }
Jacob Thornton's avatar
Jacob Thornton committed
260
261
262

  }

263

Jacob Thornton's avatar
Jacob Thornton committed
264
  /* TYPEAHEAD PLUGIN DEFINITION
265
   * =========================== */
Jacob Thornton's avatar
Jacob Thornton committed
266

267
  $.fn.typeahead = function (option) {
Jacob Thornton's avatar
Jacob Thornton committed
268
269
270
271
272
273
274
275
276
277
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
278
279
    source: []
  , items: 8
280
281
  , menu: '<ul class="typeahead dropdown-menu"></ul>'
  , item: '<li><a href="#"></a></li>'
Jacob Thornton's avatar
Jacob Thornton committed
282
  , minLength: 1
Jacob Thornton's avatar
Jacob Thornton committed
283
284
285
286
  }

  $.fn.typeahead.Constructor = Typeahead

287

Jacob Thornton's avatar
Jacob Thornton committed
288
 /*   TYPEAHEAD DATA-API
289
290
291
292
293
294
295
296
297
298
299
  * ================== */

  $(function () {
    $('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      e.preventDefault()
      $this.typeahead($this.data())
    })
  })

300
}(window.jQuery);