Sadraque Santos
Sadraque Santos

Reputation: 1849

Jquery attr() not working inside click functions

I've been trying for 3 days figure out why the attr() isn't working inside functions in Jquery. It may look like the question has already been answered but none of them is working for me.

I'm trying to change the data-text atribute from a tweet button to tweet the current text.

Here is my code:

$(".twitter-share-button").attr("data-text", "Hello World"); //Working

$("#change").on("click", function() {
    $(".twitter-share-button").attr("data-text", "Hello Universe"); // Not working
});

Example in Jsfiddle: https://jsfiddle.net/ooneskbe/

Upvotes: 0

Views: 472

Answers (2)

Xupitan
Xupitan

Reputation: 1681

$(".twitter-share-button").attr("data-text", "Hello World");
var dataObj = $(".twitter-share-button").data();
$("#change").on("click", function() {
    dataObj.text = "Hello Universe";
    $(".twitter-share-button").data(dataObj);
});

try it : https://jsfiddle.net/667f171z/1/

Upvotes: 0

dotnetom
dotnetom

Reputation: 24901

Your question does not represent the whole picture. The reason why this is not working, is because of this script that you include:

<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

This script changes your HTML. If the script is not included, the generated HTML of a button is

<a class="twitter-share-button" href="https://twitter.com/share" data-show-count="false" data-size="large">Tweet</a>

However, as soon as this script is loaded and executed, your HTML becomes

<a class="btn" id="b" href="https://twitter.com/intent/tweet?original_referer=https%3A%2F%2Ffiddle.jshell.net%2F_display%2F&amp;ref_src=twsrc%5Etfw&amp;tw_p=tweetbutton&amp;url=https%3A%2F%2Ffiddle.jshell.net%2F_display%2F">
    <i></i>
    <span class="label" id="l">Tweet</span>
</a>

You can see that the new HTML does not have a class twitter-share-button. I am not sure what you are trying to achieve with the data attribute, but you need to think of some other way to do this.

Upvotes: 1

Related Questions