Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Created October 11, 2020 22:09
Show Gist options
  • Save fhdalikhan/4459fbee5a140216b3a5886d1dd362d3 to your computer and use it in GitHub Desktop.
Save fhdalikhan/4459fbee5a140216b3a5886d1dd362d3 to your computer and use it in GitHub Desktop.
For Centering a Div On Screen and accounting for the scrolling and resizing
// Define your target div / popup container here.
var popup_target = '#checkout_open';
// Call the function like this
// jQuery("#checkout_open").center();
// Attach a function to jQuery
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() + "px");
this.css("left", ( jQuery(window).width() - this.width() ) / 2+jQuery(window).scrollLeft() + "px");
return this;
}
// Bind a function for onresize
window.onresize= function () {
jQuery(popup_target).center();
};
// Bind a function for window scroll
$(window).scroll(function() {
jQuery(popup_target).center();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment