Question

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.domain.com/submit" onclick="window.location = 'http://www.domain.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.domain.com/submit" onclick="window.location = 'http://www.domain.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.

Was it helpful?

Solution

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.

OTHER TIPS

There are several ways to get the selected text, and different browsers implement different ones:

First, there's document.getSelection(), which returns the selected text as a string. Then, there's window.getSelection(), which will return a selection object. To get the raw text, use its toString() method. The IE way of getting the text uses ranges, ie document.selection.createRange().text.

I'd suggest use of a wrapper-function to make document.getSelection() available for all browsers which support any of the methods mentioned above:

if(typeof document.getSelection === 'undefined') {
    document.getSelection =
        window.getSelection ? function() {
            return window.getSelection().toString();
        } :
        document.selection ? function() {
            return document.selection.createRange().text;
        } :
        null;
}

As a side note: You should set location.href (and not location) to change the document's address.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top