Abrir un link en un popup centrado

  • 29 Abr 2015
  • jQuery

Todo el mundo odia las ventanas emergentes.. Alguien las llama ventanas emergentes? Pero como todas las cosas, cuando se usan en el lugar indicado, se convierten de un fastidio a una solución, pero pasando desapercibidas. Porque así debería ser el web. Natural. Don't make me think!

El siguiente código viene al pelo para los links que usamos para compartir a través de las redes sociales. Basta identificar con una class los vínculos. En este ejemplo usamos: sharethis

jQuery(function ($) {

  $('a.sharethis').on('click', function(e){
    var self = $(this);
    popupCenter(self.attr('href'), self.find('.rrssb-text').html(), 580, 470);
    e.preventDefault();
  });
  
  
  var popupCenter = function(url, title, w, h) {
    // Fixes dual-screen position                         Most browsers      Firefox
    var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
    var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

    var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    var left = ((width / 2) - (w / 2)) + dualScreenLeft;
    var top = ((height / 3) - (h / 3)) + dualScreenTop;

    var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

    // Puts focus on the newWindow
    if (window.focus) {
      newWindow.focus();
    }
  };
});