Search code examples
javascriptjquerytwitteralterdata-url

Change attribute of twitter link


I'm trying to change the data-url with jQuery. Currently my code looks like this.

<div id="twitterButton" title="Tweet it on Twitter"><a href="https://twitter.com/share" id="tweet" class="twitter-share-button" data-url="" data-related="jasoncosta" data-lang="en" data-size="large" data-count="none">Tweet</a></div>

<script type="text/javascript">
$(document).ready(function () {
    $('#twitterButton').click(function () {
        $('#tweet').attr("data-url", "https://www.google.com/");
    });
});</script>

As you can see I left the url-data blank so I could be sure it is only getting set in the jQuery. However whenever I click the tweet button it always opens the window with the link for the current page that I was on. Can someone explain how I can set it to be something else via jQuery or javascript?


Solution

  • You should use .data() for controlling data attributes. As Daniele states in that answer, you must also stop the event propogation on the a element using preventDefault().

    $('#twitterButton').click(function (e) {
        $('#tweet').data('url',"https://www.google.com");
        e.preventDefault();
    });