Search code examples
javascriptfacebookpopupxhtml

Launch Facebook Share Popup at Center of Screen


The following code works well and launches a facebook popup on the screen, however this popup is not centered.

<script type="text/javascript">
    function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}
</script>

<a href="http://www.facebook.com/share.php?u=<full page url to share" onClick="return fbs_click()" target="_blank" title="Share This on Facebook"><img src="images/facebookimage.jpg" alt="facebook share"></a>

Here is the script that centers a popup window:

<script type="text/javascript">
    function MyPopUpWin(url, width, height) {
        var leftPosition, topPosition;
        //Allow for borders.
        leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
        //Allow for title and status bars.
        topPosition = (window.screen.height / 2) - ((height / 2) + 50);
        //Open the window.
        window.open(url, "Window2",
        "status=no,height=" + height + ",width=" + width + ",resizable=yes,left="
        + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY="
        + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
    }
</script>

How can I update the first script so that it works in combination with the second script to result in the popup window launching in the center of the screen?


Solution

  • See if this works for you:

    <script type="text/javascript">
    function fbs_click(width, height) {
        var leftPosition, topPosition;
        //Allow for borders.
        leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
        //Allow for title and status bars.
        topPosition = (window.screen.height / 2) - ((height / 2) + 50);
        var windowFeatures = "status=no,height=" + height + ",width=" + width + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no";
        u=location.href;
        t=document.title;
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer', windowFeatures);
        return false;
    }
    </script>
    
    <!-- Please change the width and height to suit your needs -->
    <a href="http://www.facebook.com/share.php?u=<full page url to share" onClick="return fbs_click(400, 300)" target="_blank" title="Share This on Facebook"><img src="images/facebookimage.jpg" alt="facebook share"></a>