0

I've got a button like so:

<button class="facebook text-white" href='http://www.facebook.com/sharer.php?u=url.com'>
    <img src="{{ asset('assets/img/facebook.png') }}"> 
    <span>{{"share" | trans}}</span>
</button>

I've got a js file named social.js with the following contents:

$(document).ready(function(){
  $(".twitter").click(function(e) {
        e.preventDefault();
        var href = $(e.target).attr('href');
        window.open(href, "Share your stats on Twitter!", "height=300,width=550") 
    });

  $(".facebook").click(function(e) {
      e.preventDefault();
      var href = $(e.target).attr('href');
      window.open(href, "Share you stats on Facebook!", "height=300,width=550") 
  });
});

This results in weird behaviour, as sometimes the designated link does load and opens, and sometimes it just stays on about:blank.

After every click it seems totally random if it opens up the link or not.

How do I fix this flaky behaviour?

bdv
  • 1,154
  • 2
  • 19
  • 42
  • Does `console.log(href)` show the intended URL? PS: Popups are ugly. Better use a [dialog](http://jqueryui.com/dialog/) that displays the URL in an iframe. – Kijewski Mar 14 '15 at 01:56
  • Yeah it logs just fine.. Got a link for such an iframe? I don't like popups either but couldn't think of a better solution.. – bdv Mar 14 '15 at 02:00

2 Answers2

2

Using jQuery UI dialog is fairly easy: (dynamically) create a div and invoke $(div).dialog():

$('.dialog-button').click(function (ev) {
    ev.preventDefault();
    $('<div/>', {
        title: 'Your facebook link here!',
        css: {
            position: 'relative'
        },
        append: $('<iframe/>', {
            src: $(ev.target).data('href'),
            css: {
                position: 'absolute',
                left: 0, right: 0,
                top: 0, bottom: 0,
                width: '100%', height: '100%',
                border: 0
            }
        })
    }).dialog({
        modal: true, resizable: false,
        height: 200, width: 350
    });
});
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"/>
</head>
<body>
    <button class="dialog-button" data-href="http://example.com">Click me!</button>
</body>
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • 1
    Thanks for your code, Kay! A little late response, but I feel like this modal resembles a bit too much the way 'complete this survey before download' are presented.. Deserves an upvote, tho ;-) – bdv Mar 14 '15 at 16:08
1

You should use $(this) instead of e.target in your window.open.

Why? Check this SO question: Difference between $(this) and event.target?

Community
  • 1
  • 1
Andre
  • 893
  • 2
  • 9
  • 30