Reputation: 423
I need to access the data-url="some link" when the tweet button is clicked.
Using this code:
twttr.events.bind('click', function(event) {
var tweeturl = $('.twitter-share-button').data("url");
var count = $('.twitter-share-button').data("count");
console.log(tweeturl, count);
});
However the console is outputting 'undefined undefined'. Can anyone tell me why this is happening and how to fix it?
Check out the full JS Fiddle.
Much appreciated guys.
Upvotes: 1
Views: 187
Reputation: 15528
Getting the URL is easy, just use this HTML:
<div id="foo" data-url="http://ios-blog.co.uk">
<!-- other html -->
</div>
and this event handler:
twttr.events.bind('click', function(event) {
var link = $(event.target).parent().data('url');
console.log(link);
});
Twitter's javascript converts the .twitter-share-button
link into an iframe which contains the share button html. This means that when you try and select it in your code, you're actually selecting an iframe which doesn't have the data-*
attribute the link did.
You're also not able to get the contents of the iframe and find the count due to something called the Same-origin policy.
However, you are able to get the tweet count using Twitter's api:
$.ajax({
dataType: "jsonp",
url: 'http://urls.api.twitter.com/1/urls/count.json?url=http://ios-blog.co.uk',
success: function (data) {
console.log(data.count);
}
});
See this working example: http://jsfiddle.net/TDgX5/
However, this is not an officially recommended method and probably shouldn't be relied upon too heavily. There might be a better way to solve your problem, what are you using the count for?
Upvotes: 2
Reputation: 16116
It looks like the twitter API is changing your link and putting it into a IFrame. So the link is longer accessible. I may need to better understand what your after to properly answer your question.
But could you store your data in the foo element as well?
twttr.events.bind('click', function(event) {
var tweeturl = $('#foo').data("url");
var count = $('#foo').data("count");
console.log(tweeturl, count);
});
Example
Upvotes: 1