Wednesday, March 19, 2014

JavaScript: Bunch of Social Media Sharers without External Libraries

I got this main idea from earlier Facebook developer's tip about opening new window with JavaScript (generating your own share button).
After the share button was deprecated, and before it was reused again.
The script was placed inline on the anchor element. But because it was so long (the inline script), I separated the event (click) trigger and the actual script. Then, I tinkered a bit the concept, so it can be used for multiple buttons and sharing URLs.

I didn't style the buttons here, you can do it yourself.
There are plenty of button generators you can find on the internet, or maybe using your beloved CSS framework. Usually it (the CSS framework) also includes sleek buttons, such as Bootstrap, Pure, jQueryUI, Zurb, etc.

The main purpose of this is to not burden your visitors' browsers by pulling too many resources and the dynamicallamagics from the original social networks.
In another word, making your page lighter than when it wasn't.


DEMO
You can click any of these buttons and the sharing window will be shown.


CSS
This is the main wrapper styling of the buttons



ELEMENTS
These are the buttons and the wrappers stacking.



JAVASCRIPT
The main script to assign the share function to each button.


For Twitter tweet
I separated the function for tweet because Twitter can have hashtags, via (user), and the default text of the URL. You can change them to fit your own stuff.

About changing the value
  • The hashtags text won't be needing the # (sharp symbol). Just put regular word(s), separated by comma(s). Such as hashtags=something,anotherthing,lol
  • The via user text doesn't need the @. If, for instance, your user is @sumwon, then just put like, user=sumwon.
  • The text, well, it can use your server generated page title. I'm using Blogger here, I haven't tinkered that. But, if you want to have a default text for every page, then the value will be text=awesome page, or something similar.
    For Blogger blog, the post's title, you can copy the text of h3 element with the class .post-title.entry-title.

    Example (only for Twitter button):

  • If you do not want to have any of those hashtags, via, and text - just sharing the current URL, you can empty the variable via, hashtag, and text on the JavaScript. Example, text = "".


You can add more if you want, like VK, and others. Such as the buttons you saw on YouTube's video page. Add variable(s) on the JavaScript, include that (those) in the array and then add more element(s) and the onclick event for the new button(s).

You can also use <a> (anchor) element, and the <href> will be pointing to those URLs on the JavaScript example above, plus the current page URL. The URL can be manually pasted or captured using JavaScript with the same method above, the encodeURIComponent(location.href).

No comments:

Post a Comment

Tell me what you think...