Reputation: 4893
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 :)
Upvotes: 2
Views: 583
Reputation: 4051
It's worked for me:
Replace the supplied javascript snippet with an external script tag pointing to platform.twitter.com/widgets.js.
<body>
<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://example.org" data-size="large">Tweet</a>
<script src="//platform.twitter.com/widgets.js"></script>
</body>
source here
Upvotes: 0
Reputation: 4893
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.
Upvotes: 1
Reputation: 521
Instead of:
Twitter.load()
try:
$(document).ready(Twitter.load())
$(document).on('page:load', Twitter.load())
Upvotes: 0