Last active
December 31, 2015 07:09
-
-
Save andrewbranch/7952320 to your computer and use it in GitHub Desktop.
One-up Bootstrap 3.0.0–3.0.3’s method of accounting for scrollbar width when modal is open.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function courtesy of lostsource: http://stackoverflow.com/questions/13382516 | |
function getScrollbarWidth() { | |
var outer = document.createElement("div"); | |
outer.style.visibility = "hidden"; | |
outer.style.width = "100px"; | |
document.body.appendChild(outer); | |
var widthNoScroll = outer.offsetWidth; | |
outer.style.overflow = "scroll"; | |
var inner = document.createElement("div"); | |
inner.style.width = "100%"; | |
outer.appendChild(inner); | |
var widthWithScroll = inner.offsetWidth; | |
outer.parentNode.removeChild(outer); | |
return widthNoScroll - widthWithScroll; | |
} | |
// Event names are for Bootstrap 3. Adjust for Bootstrap 2. | |
$(document).ready(function() { | |
window.scrollbarWidth = getScrollbarWidth(); | |
var bodyMarginRight = $("body").css("marginRight"); | |
$(document).on("show.bs.modal", ".modal", function() { | |
if (document.body.scrollHeight > $(window).height()) { | |
document.body.style.marginRight = scrollbarWidth + "px"; | |
} | |
}).on("hidden.bs.modal", ".modal", function() { | |
document.body.style.marginRight = bodyMarginRight; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment