bdv
bdv

Reputation: 1204

window.open sometimes opens link, sometimes not

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?

Upvotes: 0

Views: 377

Answers (2)

Andre
Andre

Reputation: 893

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

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

Upvotes: 1

Kijewski
Kijewski

Reputation: 26043

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>

Upvotes: 2

Related Questions