Search code examples
sharing

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.


Solution

  • 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!