Skip to content

Instantly share code, notes, and snippets.

@valdrinkoshi
Created July 17, 2017 17:58
Show Gist options
  • Save valdrinkoshi/169ffce9bb0c22a51a034625029cbc28 to your computer and use it in GitHub Desktop.
Save valdrinkoshi/169ffce9bb0c22a51a034625029cbc28 to your computer and use it in GitHub Desktop.
sticky dialog
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
<title>Sticky dialog</title>
<base href="https://polygit.org/polymer+v2.0.1/webcomponentsjs+v1.0.1/shadycss+webcomponents+v1.0.1/paper*+v2.0.0/iron*+v2.0.0/app*+v2.0.0/neon*+v2.0.0/components/">
<script src="webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="paper-dialog/paper-dialog.html">
</head>
<body>
<style>
.tall {
height: 50vh;
}
paper-dialog {
margin: 0;
}
</style>
<div class="tall">tall div</div>
<div class="tall">tall div</div>
<div class="tall">tall div</div>
<div class="tall">
<p>tall div, try scrolling</p>
<x-sample></x-sample>
</div>
<div class="tall">tall div</div>
<div class="tall">tall div</div>
<div class="tall">tall div</div>
<dom-module id="x-sample">
<template>
<style>
:host {
display: block;
}
</style>
<button on-click="_openDialog">open</button>
<paper-dialog id="dialog"
with-backdrop
vertical-align="top"
horizontal-align="left"
on-iron-resize="_ensureNoScroll">
<h2>dialog</h2>
<p>Hello world</p>
<div class="buttons">
<button dialog-dismiss>close</button>
</div>
</paper-dialog>
</template>
<script>
// NOTE: not needed if we declare this element in a separate file and import it.
addEventListener('WebComponentsReady', function() {
Polymer({
is: 'x-sample',
ready: function() {
// Make it resize on scroll.
document.addEventListener('scroll', () => {
if (this.$.dialog.opened) {
this.$.dialog.notifyResize();
}
});
},
_openDialog: function() {
// Move it to a stacking context safe node.
document.body.appendChild(this.$.dialog);
this.$.dialog.opened = true;
},
_ensureNoScroll: function() {
if (!this.$.dialog.opened) {
return;
}
// Check if parts of this element are offscreen.
const bounds = this.getBoundingClientRect();
const dialogBounds = this.$.dialog.getBoundingClientRect();
if (bounds.top < 0) {
this.$.dialog.verticalOffset = -bounds.top;
} else if (window.innerHeight < bounds.top + dialogBounds.height) {
this.$.dialog.verticalOffset = window.innerHeight - (bounds.top + dialogBounds.height);
} else {
this.$.dialog.verticalOffset = 0;
}
}
});
});
</script>
</dom-module>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment