Showing posts with label coffeescript. Show all posts
Showing posts with label coffeescript. Show all posts

April 6, 2013

JavaScript: Use the goo.gl link shortener from your own site

Here's a quick, stripped-down version of a javascript implementation of the goo.gl link-shortener service. It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you can call shortenUrl() as many times as you'd like. For simplicity, I've only shortened one URL here. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
  var request = gapi.client.urlshortener.url.insert({
    resource: {
      longUrl: 'http://plasticsoundsupply.com'
    }
  });
  request.execute(function(response) {
    var shortUrl = response.id;
    console.log('short url:', shortUrl);
  });
};

var googleApiLoaded = function() {
  // gapi.client.setApiKey("YOUR API KEY")
  gapi.client.load("urlshortener", "v1", shortenUrl);
};

window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');

January 5, 2012

Coffeescript: HTML5 <input> placeholder attribute fallback

You want to use the new HTML5 placeholder attribute on input fields, but you also want to support older browsers. Here's a little Coffeescript class that takes an HTML element in the constructor, and uses jQuery to bind the focus and blur events to swap out text like a modern browser would without the script.
# ## HTML5 placeholder feature fallback class
class PlaceholderFallback

  constructor: (el) ->
    @el = $(el)
    @initialize()
  
  # HTML5 <input> placeholder feature detection
  browserHasPlaceholder: =>
    "placeholder" of document.createElement("input")
  
  # Reads the placeholder attribute and uses it in a javascript fallback, if needed
  initialize: =>
    if @browserHasPlaceholder() == false
      placeholderText = @el.attr 'placeholder' 
      @el.removeAttr 'placeholder'
      @el.val(placeholderText)
      @el.focus (e) ->
        if this.value == placeholderText
          this.value = ''
      @el.blur (e) ->
        if this.value == ''
          this.value = placeholderText
    else
      @el = null

# Usage:
placeholderFallback = new PlaceholderFallback( element )

December 11, 2011

Coffeescript: MapsLoader class for asynchronous loading of Google Maps API

I'm using CoffeeScript for my current project, and we needed a way to load the Google Maps API when a user hits a particular view. This static class is auto-initialized, and all you need to call is: MapsLoader.load(callbackFunction,true). If the API has already loaded, it will invoke your callback immediately. Make sure to pass the appropriate boolean if the user is on a mobile device (true), or a desktop browser (false).
class MapsLoader

  constructor: ->

  load: (successCallback,isMobileDevice) ->
    @isMobileDevice = isMobileDevice
    @successCallback = successCallback
    if @hasLoaded != true
      @loadGoogle()
    else
      @mapsLoaded()

  loadGoogle: =>
    # reference google loader callback to local method - clean up after callback
    window.loadMaps = @loadMaps 
    apiKey = "-----your-api-key-here-----"
    script = document.createElement("script")
    script.src = "https://www.google.com/jsapi?key=#{apiKey}&callback=loadMaps"
    script.type = "text/javascript"
    document.getElementsByTagName("head")[0].appendChild(script)

  loadMaps: =>
    otherParams = if @isMobileDevice then "sensor=true" else "sensor=false"
    google.load("maps", "3", {other_params: otherParams, "callback" : @mapsLoaded});

  mapsLoaded: =>
    @hasLoaded = true
    window.loadMaps = null
    if @successCallback
      @successCallback()
    @successCallback = null

@MapsLoader = new MapsLoader()