Craig Scott
Craig Scott

Reputation: 31

Twitter / Facebook Share dynamic URL

I am trying to create a custom share link so on click it will share the current URL. I understand this

<a href="http://twitter.com/share?text=An%20Awesome%20Link&url=http://www.google.com">
Share This on Twitter</a>

But is there any way to make it dynamic, so it will grab the URL of the page the user is on and share that, rather than a hard coded link.

Thanks

Upvotes: 2

Views: 4767

Answers (3)

Rahul Shah
Rahul Shah

Reputation: 1407

Use this

<a data-count='horizontal' expr:href='data:post.canonicalUrl' href='http://twitter.com/share' rel='nofollow' target='_blank'>Share on twitter</a>

Putting expr:href='data:post.canonicalUrl' does the trick.

nonetheless,twiiter gives you an option while generating buttons
(source: ctrlv.in)

Upvotes: 0

Joan Caron
Joan Caron

Reputation: 1970

In Javascript you can use :

document.URL

It gives you the current url

https://developer.mozilla.org/en-US/docs/DOM/document.URL

and

document.title

for getting the title of this page

https://developer.mozilla.org/en-US/docs/DOM/document.title

with jQuery or javascript you can set the href attribute

http://docs.jquery.com/Attributes/attr

https://developer.mozilla.org/en-US/docs/DOM/stylesheet/href

Example:

$('a').on('click', function() {
    $(this).attr('href', 
        'http://twitter.com/share?text='+document.title+'&url=' + document.URL);
});

Another way:

https://dev.twitter.com/docs/tweet-button

Upvotes: 2

Piet van Dongen
Piet van Dongen

Reputation: 1639

With jQuery:

$('a').on('click', function() {
    document.location = 'http://twitter.com/share?text=' + document.title + '&url=' + window.location.href;
}); 

Upvotes: 0

Related Questions