Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Share button dynamic URL share

I'm trying to make a custom Twitter button that will grab the page URL of the current page when clicked, which would obviously change dependent on which page it appears on, not unlike the default share button. However, I am unsure how to pass the page URL into the button.

This is what I have thus far jsfiddle

<style type="text/css" media="screen">

</style>
<div id="social-share-container">
<div id="custom-tweet-button">
 <a id="tweetShare" href="https://twitter.com/share?url="+encodeURIComponent(document.URL); target="_blank">Tweet
    </a>
</div>
</div>

It's a bit hacked together as I'm pretty unfamiliar with JS.

like image 379
RyanSoper Avatar asked Oct 07 '13 14:10

RyanSoper


2 Answers

This passes the url and title to a simple pop-up box with the twitter share page:

<script language="javascript">
    function tweetCurrentPage()
    { window.open("https://twitter.com/share?url="+ encodeURIComponent(window.location.href)+"&text="+document.title, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false; }
</script>

<a class="tweet" href="javascript:tweetCurrentPage()" target="_blank" alt="Tweet this page">Tweet this page</a>

If you don't want it to open in a popup box, you can use this instead of window.open:

window.location.href="https://twitter.com/share?url="+ encodeURIComponent(window.location.href)+"&text="+document.title;

Update: escape() function is deprecated, Replaced with encodeURIComponent()

like image 61
wentz Avatar answered Oct 06 '22 06:10

wentz


I would suggest window.location - That will give you the current page url.

Problem is you're using JS inline in HTML - you can't do that like you're wanting to.

I updated your fiddle with some vanilla js to show you a better way to do this.

http://jsfiddle.net/4jF5N/1/

var link = document.getElementById('tweetShare');
var url = window.location;

link.addEventListener('click',function(event){
    event.preventDefault();

    window.open("https://twitter.com/share?url="+encodeURIComponent(url));
    alert(url)
},false);
like image 21
Drew Dahlman Avatar answered Oct 06 '22 06:10

Drew Dahlman