DaniG2k DaniG2k - 1 month ago 7
CoffeeScript Question

Rails 4: getting Twitter share button to work with Turbolinks

I'm trying to get the Twitter share button to work with a Rails 4 app + Turbolinks.

In my view, I have:

<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-text="<%= @article.title %>" data-via="<%= t('twitter_user') %>">Tweet</a>


I also have a twitter.js.coffee file in my app/assets/javascripts/ directory:

class @Twitter
eventsBound = false
@load: ->
Twitter.loadTwitterSDK()
Twitter.bindEvents() unless Twitter.eventsBound
@bindEvents: ->
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
$(document).on('page:load', Twitter.renderTweetButtons)
Twitter.eventsBound = true
@renderTweetButtons: ->
$('.twitter-share-button').each ->
button = $(this)
button.attr('data-url', document.location.href) unless button.data('url')?
button.attr('data-text', document.title) unless button.data('text')?
@loadTwitterSDK: ->
$.getScript("//platform.twitter.com/widgets.js")
Twitter.load()


The button appears when I hard refresh the page but disappears when navigating (likely due to Turbolinks). I probably need to keep calling the renderTweetButtons function, but am not sure how.

Any help appreciated! Thanks :)

Answer

The issue was that I was missing twttr.widgets.load() within @renderTweetButtons as documented here. This is what the complete file looks like now:

class @Twitter
    eventsBound = false
    @load: ->
        Twitter.loadTwitterSDK()
        Twitter.bindEvents() unless Twitter.eventsBound
    @bindEvents: ->
        if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
            $(document).on('page:load', Twitter.renderTweetButtons)
        Twitter.eventsBound = true
    @renderTweetButtons: ->
        $('.twitter-share-button').each ->
            button = $(this)
            button.attr('data-url', document.location.href) unless button.data('url')?
            button.attr('data-text', document.title) unless button.data('text')?
        twttr.widgets.load()
    @loadTwitterSDK: ->
        $.getScript("//platform.twitter.com/widgets.js")
Twitter.load()

That solved the issue.

Comments