bootstrap snippets

Bootstraping your database with rake

Tagged bootstrap, ruby, rails, rake  Languages ruby

In lib/tasks/app.rake:

namespace :db do
  desc "Bootstraps the database"
  task :bootstrap => ['db:schema:load'] do

   { 'Ruby' => 'ruby',
      'JavaScript' => 'javascript',
    }.each do |name, short_name|
      Category.create!(:name => name, :short_name => short_name)
    end

  end
end

A Reusable JavaScript Modal Dialog Based on Bootstrap Modal

Tagged bootstrap, modal, javascript, coffeescript  Languages coffeescript

The Coffeescript class:

root = exports ? this

class Modal
  constructor: (options = {}) ->
    @options = options
    @id = options.id ? 'modal-dialog-' + Math.round((Math.random() * 1000))
    @dom_id = "##{@id}"
    @onPrimaryButton = options.onPrimaryButton ? ->
    @onSecondaryButton = options.onSecondaryButton ? ->
    @template = options.template ? HandlebarsTemplates['modal'](id: @id)
    @render()

  render: ->
    $('body').append(@template)
    @modal = $(@dom_id)
    _this = this
    @modal.find('.btn-primary').on 'click', ->
      _this.onPrimaryButton(this)
    @modal.find('.btn-secondary').on 'click', ->
      _this.onSecondaryButton(this)

  setButtonText: (primary, secondary) ->
    @modal.find('.btn-primary').html(primary)
    @modal.find('.btn-secondary').html(secondary)

  setTitle: (title) ->
    @modal.find('.title').html(title)

  setBody: (body) ->
    @modal.find('.body').html(body)

  show: ->
    @modal.modal('show')

  hide: ->
    @modal.modal('hide')

root.Modal = Modal

The view (bootstrap 2.3.2):

<div class="modal hide fade" id="{{id}}">
  <div class="modal-header">
    <button aria-hidden="true" class="close" data-dismiss="modal" type="button"> &times;</button>
    <h3 class="title"></h3>
  </div>
  <div class="modal-body body">
  </div>
  <div class="modal-footer">
    <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
    <button class="btn btn-primary" data-dismiss="modal">Ok</button>
  </div>
</div>

Usage, e.g.:

class Notifications
  constructor:  ->
    @modal = new Modal
      onPrimaryButton: $.proxy(@onItemDelete, this)
      onSecondaryButton: $.proxy(@onItemRead, this)
  onItemDelete: ->
    # do something when primary button was clicked
  onItemRead: ->
    # do something when secondary button was clicked

Autocomplete / Typeahead

Tagged autocomplete, javascript, typeahead, bootstrap, jquery  Languages javascript, html

Javascript (jQuery):

function autocomplete(options) {
  var input = $(options.input);
  var resultsElem = $(options.results);
  var url = options.url;
  var cache = {};
  var result = null;
  var minQueryLength = options.minQueryLength;
  var debounce = null;
  var waitingFor = null; // Ajax responses might not arrive in order
  var show = function() {
    if(result == null) {
      return;
    }
    resultsElem.fadeIn(100);
  };
  var hide = function() {
    resultsElem.fadeOut(100);
  };
  // Hide when clicking outside autocomplete elements
  $('body').click(function(){
    hide();
  });
  // Stop propagation so that event does not reach the body handler 
  $('.autocomplete').click(function(e){
    e.stopPropagation();
  });
  var renderResults = function(query, results) {
    if (query !== waitingFor) {
      return;
    }
    resultsElem.html(results);
    if (results != undefined) {
      show();
    } else {
      hide();
    }
  };
  var search = function() {
    var query = input.val();
    console.log("Searching for '" + query + "'")
    waitingFor = query;
    if (query in cache) {
      console.log('Using cache')
      renderResults(query, cache[query]);
    } else {
      console.log('Not using cache')
      if (query.length > minQueryLength) {
        $.ajax({url: url, data: {query: query}, type: 'GET'}).then(function(data) {
          result = data;
          cache[query] = result;
          renderResults(query, result);
        });
      } else {
        renderResults(query, null);
      }
    }
  };
  var searchWithDebounce = function(e) {
    clearTimeout(debounce);
    debounce = setTimeout(search, 100);
  };
  input.on('blur', hide);
  input.on('focus', show);
  input.on('keyup', searchWithDebounce);
};

autocomplete({
  input: '#autoComplete',
  results: '#autocomplete-results',
  url: '/search',
  minQueryLength: 2
});

HTML (Bootstrap 4):

<form action="/search" class="form-inline ml-2 my-2 my-lg-0 ml-auto mr-auto" id="site-search" method="GET">
  <input aria-label="Search" autocomplete="off" class="autocomplete form-control mr-sm-2" id="autoComplete" name="query" placeholder="Search" tabindex="1" type="search">
  <div class="autocomplete shadow" id="autocomplete-results"></div>
</form>