javascriptjquerysocial-networkingshare-button

Multiple social share buttons with different links


I have implemented a jQuery social sharing solution on my website with the help of this article. I had to modify the code since I have multiple posts on one page with these buttons. I have set a 'data-href' attribute for the buttons container in PHP, which shows the correct link for every post, but the script only gets the attribute of the first one, so every popup window tries to share the same post. How should I modify this code to get the different 'data-href' values?

$(document).ready(function(){
var pageTitle   = document.title; //HTML page title
var pageUrl     = $('.share-btn-wrp').attr('data-href');

$('.share-btn-wrp li').click(function(event){
    var shareName = $(this).attr('class').split(' ')[0]; //get the first class name of clicked element
    switch(shareName) //switch to different links based on different social name
    {
        case 'facebook':
            OpenShareUrl('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(pageUrl) + '&title=' + encodeURIComponent(pageTitle));
            break;
        case 'twitter':
            OpenShareUrl('http://twitter.com/home?status=' + encodeURIComponent(pageTitle + ' ' + pageUrl));
            break;
        case 'email':
            OpenShareUrl('mailto:?subject=' + pageTitle + '&body=Found this useful link for you : ' + pageUrl);
            break;
    }

});

function OpenShareUrl(openLink){
    //Parameters for the Popup window
    winWidth    = 650; 
    winHeight   = 450;
    winLeft     = ($(window).width()  - winWidth)  / 2,
    winTop      = ($(window).height() - winHeight) / 2,
    winOptions   = 'width='  + winWidth  + ',height=' + winHeight + ',top='    + winTop    + ',left='   + winLeft;
    window.open(openLink,'Share This Link',winOptions); //open Popup window to share website.
    return false;
}
});

The structure of one sharing block is the following:

<ul class="share-btn-wrp" data-href="<?php echo $this->item->link; ?>">
  <li class="facebook button-wrap"></li>
  <li class="twitter button-wrap"></li>
  <li class="email button-wrap"></li>
</ul>

Solution

  • It looks like you need to get the data-href of the parent container of the clicked button. Try this:

    $('.share-btn-wrp li').click(function(event){
        var pageUrl = $(this).closest('.share-btn-wrp').attr('data-href');
        var shareName = $(this).attr('class').split(' ')[0]; //get the first class name of clicked element
        switch(shareName) //switch to different links based on different social name
        {
     //etc