Reputation: 154
Good day everyone!
When I click on a div I want overflow of body to become hidden and add a right margin to body of the scrollbar width. Here is my jQuery:
var getScrollbarWidth = function () {
var scrollElement = document.createElement("div"); // Create element
scrollElement.addClass("scrollbar-element"); // Apply predefined style
document.body.appendChild(scrollElement); // Add element to page
var scrollbarWidth = scrollElement.offsetWidth - scrollElement.clientWidth; // Subtract width without scrollbar from width with scrollbar
document.body.removeChild(scrollElement); // Remove element from page
return scrollbarWidth;
};
$(".thumbnail").on("click", function () {
$(".project-wrap").addClass("project-open");
$("body").attr("margin-right", getScrollbarWidth() + "px");
$(".project-button").attr("margin-right", getScrollbarWidth() + "px");
$("body").addClass("body-overflow");
}
And css:
.body-overflow
overflow: hidden !important
.project-open
display: block !important
The issue is that if "$("body").addClass("body-overflow");" is in the end, it doesn't work, but if it is on the first line of thimbnail click function, then body margin is not applied.
Upvotes: 2
Views: 98
Reputation: 1927
Try to store your scrollbar width in a variable before you add the body-overflow
class.
Like:
$(".thumbnail").on("click", function () {
var scrollbarWidth = getScrollbarWidth();
$("body").addClass("body-overflow");
$("body").attr("margin-right", scrollbarWidth + "px");
$(".project-wrap").addClass("project-open");
$(".project-button").attr("margin-right", scrollbarWidth + "px");
});
Upvotes: 2