set Tweet button 'data-text' contents dynamically with javascript, or..?

╄→尐↘猪︶ㄣ 提交于 2019-12-04 11:20:56

Just put it in a container with a known ID and traverse the document with it:

<div id="someIDiKnow">
    <a id="tweetBtnId"...>...</a>
</div>

$("#someIDiKnow a").attr("data-text", "Replacement Text!");

Looks like it's going to be the kludgy hidden form/php variable approach for now -- I'll post back if I find a better work-around.

EDIT: the hidden-form/PHP variable solution has beaten the roadblock put up by Twitter's Tweet button -- I can now successfully, dynamically change the Tweet button text at will, anytime based on the user's client-side input. Per Domenic's astute observation that the question above is too long and has code in it, I'll skip posting the answer here, and I apologize for the length above.

You could use JQuery to update the attribute data-text by adding an onclick action on the image. If you wanted to include the text inside the actual image tag by adding your own attribute to the tag, that could be an easy work around to assembling the tweet text.

For example:

function updateTweetBtn(obj) {
   $('#someIDiKnow a').attr('data-text', $(this).attr('tweet'));
}

<img src="/images/myimage.jpg" tweet="This is what I want to tweet" onclick="updateTweetBtn(this);" />
<img src="/images/myimage2.jpg" tweet="This is some other text I want to tweet" onclick="updateTweetBtn(this);" />

using in html

<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<a href="http://twitter.com/share" class="twitter-share-button" data-text="old text">Tweet</a>

I managed to change the 'data-text' with javascript

var a = "new text";
document.getElementsByClassName('twitter-share-button')[0].setAttribute("data-text", a);

also worked with document.getElementById('twitter') if you add id='twitter' to <a>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!