Question

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?

Était-ce utile?

La 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();
});

Autres conseils

You must call the preventDefault() method to stop the propagation of the click event on the child a element:

Try this code:

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

Good code

D.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top