Skip to content

Instantly share code, notes, and snippets.

@bendasvadim
Last active January 27, 2018 20:25
Show Gist options
  • Save bendasvadim/9ea0ca4000743d2c7028abebfd2df95c to your computer and use it in GitHub Desktop.
Save bendasvadim/9ea0ca4000743d2c7028abebfd2df95c to your computer and use it in GitHub Desktop.
Поделиться в соц. сетях
// Все элементы класса .social_share считаем кнопками шаринга
$(document).on('click', '.social_share', function(){
Share.go(this);
});
// Пример кнопок с минимальной настройкой
<p>Поделиться:
<button class="social_share" data-type="vk">ВКонтакте</button>
<button class="social_share" data-type="fb">Facebook</button>
<button class="social_share" data-type="tw">Twitter</button>
<button class="social_share" data-type="lj">LiveJournal</button>
<button class="social_share" data-type="ok">Одноклассники</button>
<button class="social_share" data-type="mr">Mail.Ru</button>
</p>
Share = {
/**
* Показать пользователю дилог шаринга в сооветствии с опциями
* Метод для использования в inline-js в ссылках
* При блокировке всплывающего окна подставит нужный адрес и ползволит браузеру перейти по нему
*
* @example <a href="" onclick="return share.go(this)">like+</a>
*
* @param Object _element - элемент DOM, для которого
* @param Object _options - опции, все необязательны
*/
go: function(_element, _options) {
var
self = Share,
options = $.extend(
{
type: 'vk', // тип соцсети
url: location.href, // какую ссылку шарим
count_url: location.href, // для какой ссылки крутим счётчик
title: param('title'), // заголовок шаринга
image: param('image'), // картинка шаринга
text: param('description'), // текст шаринга
},
$(_element).data(), // Если параметры заданы в data, то читаем их
_options // Параметры из вызова метода имеют наивысший приоритет
);
if (self.popup(link = self[options.type](options)) === null) {
// Если не удалось открыть попап
if ( $(_element).is('a') ) {
// Если это <a>, то подставляем адрес и просим браузер продолжить переход по ссылке
$(_element).prop('href', link);
return true;
}
else {
// Если это не <a>, то пытаемся перейти по адресу
location.href = link;
return false;
}
}
else {
// Попап успешно открыт, просим браузер не продолжать обработку
return false;
}
function param(name) {
return $('meta[property=og\\:' + name + ']').attr('content');
}
},
// ВКонтакте
vk: function(_options) {
var options = $.extend({
url: location.href,
title: document.title,
image: '',
text: '',
}, _options);
console.log('http://vkontakte.ru/share.php?'
+ 'url=' + encodeURIComponent(options.url)
+ '&title=' + encodeURIComponent(options.title)
+ '&description=' + encodeURIComponent(options.text)
+ '&image=' + encodeURIComponent(options.image)
+ '&noparse=true');
return 'http://vkontakte.ru/share.php?'
+ 'url=' + encodeURIComponent(options.url)
+ '&title=' + encodeURIComponent(options.title)
+ '&description=' + encodeURIComponent(options.text)
+ '&image=' + encodeURIComponent(options.image)
+ '&noparse=true';
},
// Одноклассники
ok: function(_options) {
var options = $.extend({
url: location.href,
text: '',
}, _options);
return 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1'
+ '&st.comments=' + encodeURIComponent(options.text)
+ '&st._surl=' + encodeURIComponent(options.url);
},
// Facebook
fb: function(_options) {
var options = $.extend({
url: location.href,
title: document.title,
image: '',
text: '',
}, _options);
return 'http://www.facebook.com/sharer.php?s=100'
+ '&p[title]=' + encodeURIComponent(options.title)
+ '&p[summary]=' + encodeURIComponent(options.text)
+ '&p[url]=' + encodeURIComponent(options.url)
+ '&p[images][0]=' + encodeURIComponent(options.image);
},
// Живой Журнал
lj: function(_options) {
var options = $.extend({
url: location.href,
title: document.title,
text: '',
}, _options);
return 'http://livejournal.com/update.bml?'
+ 'subject=' + encodeURIComponent(options.title)
+ '&event=' + encodeURIComponent(options.text + '<br/><a href="' + options.url + '">' + options.title + '</a>')
+ '&transform=1';
},
// Твиттер
tw: function(_options) {
var options = $.extend({
url: location.href,
count_url: location.href,
title: document.title,
}, _options);
return 'http://twitter.com/share?'
+ 'text=' + encodeURIComponent(options.title)
+ '&url=' + encodeURIComponent(options.url)
+ '&counturl=' + encodeURIComponent(options.count_url);
},
// Mail.Ru
mr: function(_options) {
var options = $.extend({
url: location.href,
title: document.title,
image: '',
text: '',
}, _options);
return 'http://connect.mail.ru/share?'
+ 'url=' + encodeURIComponent(options.url)
+ '&title=' + encodeURIComponent(options.title)
+ '&description=' + encodeURIComponent(options.text)
+ '&imageurl=' + encodeURIComponent(options.image);
},
// Google+
gg: function (_options) {
var options = $.extend({
url: location.href
}, _options);
return 'https://plus.google.com/share?url='
+ encodeURIComponent(options.url);
},
//LinkedIn
li: function(_options) {
var options = $.extend({
url: location.href,
title: document.title,
text: ''
}, _options);
return 'http://www.linkedin.com/shareArticle?mini=true'
+ '&url=' + encodeURIComponent(options.url)
+ '&title=' + encodeURIComponent(options.title)
+ '&summary=' + encodeURIComponent(options.text);
},
// Открыть окно шаринга
popup: function(url) {
return window.open(url,'','toolbar=0,status=0,scrollbars=1,width=626,height=436');
}
}
// Все элементы класса .social_share считаем кнопками шаринга
$(document).on('click', '.social_share', function(){
Share.go(this);
});
function fbShare(siteUrl, picture, title, caption, descr, winWidth, winHeight) {
var winTop = (screen.height / 2) - (winHeight / 2);
var winLeft = (screen.width / 2) - (winWidth / 2);
window.open('http://www.facebook.com/sharer.php?s=100&u=' + siteUrl + '&picture=' + picture + '&title=' + title + '&caption=' + caption , '&description=' + descr, 'top=' + winTop + ',left=' + winLeft + ',toolbar=0,status=0,width=' + winWidth + ',height=' + winHeight);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment