Mousewheel prevent body scroll on modal
Solution #1
// prevent background of modal from scrolling
// DOMMouseScroll for Firefox equivalent
$(document).on("mousewheel DOMMouseScroll", ".modal-backdrop, .modal-body", function(event) {
event.stopPropagation();
event.preventDefault();
});
// prevent background of modal from scrolling
var keysThatScroll = new Array(33,34,35,36,37,38,39,40);
var DEBUG_KEY_SCROLL_PREVENTION = false;
$(document).on("keydown", function(event) {
var key = event.which;
if ($.inArray(key,keysThatScroll) === -1) {
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("no worries for this key", key);
return true; // no worries for this key
}
if ($(".modal-backdrop").length === 0) {
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("no modification when modal is off");
return true; // no worries for these keys
}
if (event.target == null || event.target.tagName == null) { // should not happen
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("event.target or event.target.tagName is null or undefined");
return true;
}
if (event.target.tagName.toLowerCase() === "body") {
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("keydown, on body, stopping");
event.preventDefault();
return false;
}
if (event.target.type == null) {
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("keydown, no type and not body, letting go");
return true; // ok keep going
}
var type = event.target.type.toLowerCase();
if (DEBUG_KEY_SCROLL_PREVENTION) console.log("keydown, type", type);
if (type == 'input' || type == 'text' || type == 'textarea' ||type == 'select') {
// normal keyup and keydown allowed in modals
return true; // ok keep going
}
// stop scrolling keys in modal of further effects, for example if focus is on a button and keydown
event.preventDefault();
event.stopPropagation();
return false; // in jQuery returning false does the same as preventDefault and stopPropagation
});
Solution #2
// extend Bootstrap modal to remove scrollbar during modal show
var _show = $.fn.modal.Constructor.prototype.show;
$.fn.modal.Constructor.prototype.show = function() {
_show.apply(this, arguments);
$("body").addClass("modal-on");
};
var _hide = $.fn.modal.Constructor.prototype.hide;
$.fn.modal.Constructor.prototype.hide = function() {
_hide.apply(this, arguments);
$("body").removeClass("modal-on");
};
along with CSS
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
overflow-y: scroll;
}
body.modal-on {
overflow:hidden;
}
Recent Comments