Share link centered pop-up via Javascript

Post Photo
Friday, 18th September 2020

Almost every website uses social sharing links. It helps your visitors share your post or page or whatever. But these links open in a new tab or even worse in the same page. This few lines of Javascript open a nice centered pop-up window for your users

No jQuery required. It's written in Vanilla Javascript.

Just copy and paste and your links now will open beautifully in a new centered window.

Enjoy!

/**
* Share Pop-up
*/

const shareIt = document.querySelectorAll('.share-it');

shareIt.forEach(item => {
    item.addEventListener('click', (e) => {
    e.preventDefault();
    PopupCenter(item.href,'Share','700','600');
})
});

/**
* Pop-up Window Centered
*/

function PopupCenter(url, title, w, h) {
    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 / 2) - (h / 2)) + dualScreenTop;
    var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    if (window.focus) {newWindow.focus();}
}

Share Post

If you like this post please share with your friends