Learning Learning - 23 days ago 4
Javascript Question

Custom Share using Javascript not working as desired

I am working on a simple custom share where user will click on the share button which will show list of share option and then user can click on any one of them to share the page.

I have setup code on CodePen not sure why it is not working.

<html>

<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>

<meta charset="utf-8">
<title>JS Bin</title>
</head>

<body>
<a class="share-btn" href="#">S</a>
<div class="share"><a href="http://www.facebook.com/sharer/sharer.php?u=http://domain.com"> F</a>
</div>

<div class="share"><a href="whatsapp://send?text=The text to share!" data-action="share/whatsapp/share">W</a></div>

<div class="share"><a href="http://twitter.com/intent/tweet?status=This is the Title+http://domain.com/article/this-is-article
">T</a></div>


</body>

</html>


jQuery(document).ready(function($) {
$('.share').click(function() {
var NWin = window.open($(this).prop('href'), '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
if (window.focus) {
NWin.focus();
}
return false;
});
});

$(".share-btn").click(function() {
$(".share").toggle();
});

Answer

Change $('.share').click to $('.share > a').click else the $(this) refers to the div which has no property called href.

Here is an example for it: http://codepen.io/anon/pen/rWObQo

$('.share > a').click(function() {
Comments