Ad

How Do I Get This "Share" Button To Grab The Current URL's HTML Title In Addition To URL?

I'm a JavaScript novice trying to build a basic share button as a learning project. I'm a bit stumped about one aspect. While I can grab the URL of the current page and pass that into the URL that prepopulates the share form, I'm not sure how to grab the HTML title.

Here's what I have to far:

<a href="http://www.example.com/submit" onclick="window.location = 'http://www.example.com/submit?url=' + encodeURIComponent(window.location); return false;"> Share This </a> 

What do I add to the onclick section to get the current page's title as well? Whatever it is would be passed as title= in the URL.

Bonus: Is there something I can add to send along some highlighted text from the current page? That would go in the URL as body=

So I'm looking to fill in these blanks:

<a href="http://www.example.com/submit" onclick="window.location = 'http://www.example.com/submit?url=' + encodeURIComponent(window.location); return false; + 'title=' + SOMETHING + 'body=' + SOMETHING'"> Share This </a>

At least I think so. I'm not 100% sure I've got the +'s and ''s in the right place.

Ad

Answer

I think you want document.title. Getting selected text is a bit more complicated, especially if you want to support IE. DOM standard is window.getSelection but for IE you have to mess around with ranges - I've not checked if things have improved in IE8.

Also I meant to ask, where will the share button be? If it's in the page then clicking on the button is going to de-select the text which is selected.

Ad
source: stackoverflow.com
Ad