Kyle
Kyle

Reputation: 347

Is there a way to make a Facebook/Twitter share button that shares a div's innerHTML?

Here is a CodePen that helps explain what I'm doing.

I have a site that generates a random fact with Javascript, and puts it into a div with the id="fact". Below this div is a simple "Share on Twitter" link using a very basic sharing link I found online:

http://twitter.com/share?url=http://www.thewikifix.com&text=Simple Share Buttons&hashtags=thewikifix

This works great and it's very simple, but I'm wondering if there's a way to share the contents of the

<div id="fact"></div>.

Basically, instead of

"text=SimpleShareButtons"

it would be

"text={document.getElementId("fact").innerHTML}"

(Obviously the second part is fictional, I know I can't just put a Javascript string into a link in HTML).

Is there a way to do what I'm doing? Even a completely different way of doing this is welcome as well.

Upvotes: 0

Views: 1086

Answers (2)

wahwahwah
wahwahwah

Reputation: 3177

There's two changes that were made to the HTML for simplicity's sake. Here's a fiddle the code that should do what you're looking for:

[css not changed]

HTML:

<p id="fact">Babe Ruth once pitched a 4-pitch walk to start a game, got angry at the umpire's calls, and punched him, getting ejected. Reliever Ernie Shore came in and retired every batter for a combined no-hitter.</p>
<p id="sharing"><a id="factLink" href="#" target="_blank">share on twitter</a>
</p>

JS/JQUERY:

 $('#factLink').click(function () {

    // Get the fact text
    var factText = $('#fact').text();

    // Convert to string
    var factStr = factText.toString();

    // Fact length
    var factLen = factText.length;

    // This section formats the text that is too long, remove it if needed
    if (factLen > 103) { // max chacters allowed
        // trim, and allow space for '...'"
        var trimFact = factStr.substring(0, 100);
        var trimFact = trimFact.trim(); //<-- ensures the last character isnt ' '
        factStr = trimFact + "...";
    }

    // Update the link
    var linkRef = "http://twitter.com/share?url=http://www.thewikifix.com&text=" + factStr + "&hashtags=thewikifix";

    $('#factLink').attr('href', linkRef);

});

Hope this helps!

Upvotes: 1

Shan Robertson
Shan Robertson

Reputation: 2742

Your psudo code is pretty much exactly what you want to do. You just need to pass it as a variable

var inner = document.getElementId("fact").innerHTML;
"text=" + inner

Upvotes: 0

Related Questions