Reputation: 3
I am trying to find a way (JQuery etc.) of auto updating the URL for sharing on Facebook, Twitter etc.
For example:
<a href="https://www.facebook.com/sharer/sharer.php?u=http//xxxxxxxxx.co.uk/index.html/" class="button button--icon button--facebook"><img src="../img/facebook.png"></a>
Except I want to replace "http//xxxxxxxxx.co.uk" with something so that if the URL of that page were to change, it would grab that URL and insert it into the tag, without me having to update it manually?
Upvotes: 0
Views: 4405
Reputation: 3314
Using jQuery
you can do something like this on document.ready
:
Here is a jsFiddle demo
$(function () {
var fbShare = 'https://www.facebook.com/sharer/sharer.php?u='
// grab url of the page:
var url = window.location;
// loop through all elements with class 'button--facebook' and update href:
$('.button--facebook').each(function () {
$(this).attr('href', fbShare + url);
});
});
Upvotes: 0
Reputation: 5634
Here is a small function to generate share buttons with jQuery.
HTML
<div id="fb"></div>
jQuery
var fblink = "https://www.facebook.com/sharer/sharer.php?u={{link}}";
$(document).ready(function () {
generateLink('fb','http://www.google.com');
generateLink('fb','http://www.stackoverflow.com');
});
function generateLink(id,link) {
$('#' + id).append('<a href="' + fblink.replace('{{link}}',link) + '">Share</a>');
}
I replaced you image with "Share" for completeness in JSFiddle without access to your image, but that can be replaced to suit your needs.
Upvotes: 0
Reputation: 219037
Do you just mean that you want to dynamically build this href
from the current page's URL? Something like this?:
document.getElementById('yourAnchorElement').href =
'https://www.facebook.com/sharer/sharer.php?u=' +
encodeURIComponent(window.location.href);
It just gets the current URL, URL-encodes it to be used as a query string parameter, appends it to the known base URL, and sets it to the href
of the element.
You don't need to use document.getElementById()
, any method you use to identify the target element is fine.
Upvotes: 0