Woolf Faulkner
Woolf Faulkner

Reputation: 108

<a></a> auto reference page url inside of <a></a> tag

How do I reference the current page URL?

I have a share twitter button on several pages. I would like to be able to automatically refernce the current page URL so when a user clicks "tweet this page" the URL is generated in the twitter tweet box. The reason I wish to do this is so I can manage the button from one place and not several pages.

HTML (currently, the url is manually pasted into the href tag in the link.

<a href="http://dangfoods.com/coconutchips.php" title="These chips are great for you HEALTH!! #dangfoods" class="tweetDialog" target="_blank"><div id="tweets-btn" class="custom-button">Tweet This Page</div></a>

Current Javascript

// We bind a new event to our link
$('a.tweetDialog').click(function(e){
  //We tell our browser not to follow that link
  e.preventDefault();
  //We get the URL of the link
  var loc = $(this).attr('href');
  //We get the title of the link
  var title  = escape($(this).attr('title'));
  //We trigger a new window with the Twitter dialog, in the middle of the page
  window.open('http://twitter.com/share?url=' + loc + '&text=' + title + '&', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
});

Upvotes: 0

Views: 229

Answers (2)

Fabio S.
Fabio S.

Reputation: 21

You can use "location.href" to get URL of the page and "document.title" to get the title of the current page. Try this:

$('a.tweetDialog').click(function(e){
    //We tell our browser not to follow that link
    e.preventDefault();

    //We get the URL of the link
    var loc = location.href;
    //We get the title of the link
    var title  = escape(document.title);

    //We trigger a new window with the Twitter dialog, in the middle of the page
    window.open('http://twitter.com/share?url=' + loc + '&text=' + title + '&', 'twitterwindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
});

Upvotes: 1

You want to use current page URL instead of href attribute? Change

var loc = $(this).attr('href');

to

var loc = location.href;

Or you could generate Twitter share URL server-side, put it in href attribute, then in onclick stop default handler and open window with link target. That way your link would work without JavaScript.

Upvotes: 1

Related Questions