This question comes very closely to what I'm after: Replace an Attribute in the Tweet Button with Jquery
However, the suggested solution works just once. That is, I cannot use it in my switch statement like this:
switch(element.id)
{
case "t1":
$(document).ready(function(){
$('a[data-text]').each(function(){
$(this).attr('data-text', Text_Variant_1);
});
$.getScript('http://platform.twitter.com/widgets.js');
});
break;
case "t2":
$(document).ready(function(){
$('a[data-text]').each(function(){
$(this).attr('data-text', Text_Variant_2);
});
$.getScript('http://platform.twitter.com/widgets.js');
});
...
}
What happens is that the data-text attribute is set according to whichever case happens first and doesn't change afterwards.
How can I change data-text attribute of a Tweet Button as many times as I need?
Update: here's the page I'm working on: http://zhilkin.com/socio/en/
The Traits table can be safely ignored. What I want to do with the Sociotypes table is that when you click on a type, the data-text of the Tweet Button below the description on the right should be changed accordingly.
Right now it works like this: if I hover on or click "Don Quixote", then data-text is set to "... Don Quixote ...", and it stays the same if I click "Dumas" later. And vice versa: if I hover on or click "Dumas", then data-text is set to "... Dumas ..." and doesn't change if I click "Don Quixote". (Other types are empty at the moment.)
So, the Tweet Button is only changed the first time I run the script, but I need it to be updated as many times as the type changes.
I struggled with this for a couple of hours this morning, but finally got it working! The problem is essentially that you can only include the twitter widgets.js script once in the page, and that script evaluates the data-text
attribute on load. Therefore, in your example, you dynamically set the data-text
attribute before loading the script, which will work as expected. However, you can then make no further updates as the script has already run.
I saw this article suggesting you can call twttr.widgets.load()
again at runtime to re-evaluate and re-render the buttons, however that didn't work for me. This is because that function re-evaluates <a>
tags, not <iframe>
tags!
So the solution, as pointed out here, is to completely remove the rendered <iframe>
from the DOM, then make a new <a>
element with all the appropriate attributes before calling twttr.widgets.load()
to finally re-evaluate it and turn it into an <iframe>
.
Please see this fiddle for a working example!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With