Pinterest-Style Modal Popup Scrolling in Javascript
I have been working on a modal dialog that would alter the scrolling of a browser window. Essentially I have a page with a lot of content causing vertical scroll. I have a modal dialog that should pop up that also contains enough content to create vertical scrolling. The goal here is to make the browser scroll on the background content until the model is shown, and then it would switch to scrolling on the modal content.
<html>
<head>
<style type="text/css">
.container {
width: 100%;
color: #ccc;
}
.large-content {
width: 800px;
margin: 0px auto;
}
.container.active {
position: fixed;
}
.popup {
display: none;
}
.popup.active {
display: block;
position: absolute;
}
</style>
<title>Testy McTesterson's Test</title>
<script
type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div class="popup">
<p>Lots of content</p>
</div>
<div class="container">
<div class="large-content">
<p>Freaking tons of content <a href="#">Link to show modal</a></p>
</div>
</div>
</body>
</html>
Yes, I know. Put the JavaScript at the bottom blah blah blah. What I have done here though is create a page with some basic styling. I wanted the content to align center to make it a bit trickier. Once a link is clicked the modal should be shown and the background content changed to position: fixed. This ensures that the scrollbar no longer pays attention to the background content scrolling.
$(document).ready(function () {
var clickableLink = $('a'),
container = $('.container'),
popup = $('.popup'),
body = $('body'),
activePosition = 0,
popupActive = false,
win = $(window)
clickableLink.click(function (e) {
e.preventDefault()
e.stopPropagation()
var position = win.scrollTop()
// set the location of the scrolling
container.css('top', -position + 'px')
activePosition = position
// set the window to the top
win.scrollTop(0)
// add popup styling
container.addClass('active')
popup.addClass('active')
popupActive = true
})
// called if the popup is active
body.click(function (e) {
if (!popupActive) return false
// remove styling
container.removeClass('active')
popup.removeClass('active')
popupActive = false
// move the container and the scroller back
container.css('top', '0px')
win.scrollTop(activePosition)
})
})
The JavaScript basically takes the user click event handler and assigns the css classes to make the background content fixed positioning. It grabs the current scroll location, and moves the background content up that amount so it appears as though it didn’t move. Then there is another event handler to move it all back when the dialog is closed.
I hope this helps someone. I have tested it in Chrome and Internet Explorer 7+.
Make sure you specify a DOCTYPE if you would like this to work in any version of Internet Explorer as it doesn’t like position:fixed without a DOCTYPE.