Created
December 18, 2012 20:43
-
-
Save paulstraw/4331778 to your computer and use it in GitHub Desktop.
A hopefully-flexible class for JS modals. (Uses jQuery)
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
| class Modal | |
| constructor: (@content, @afterShow, @afterHide) -> | |
| hide: => | |
| $(window).off 'resize', @setPosition | |
| $('#shade').fadeOut 120, => | |
| $('#shade').remove() | |
| @afterhide?() | |
| show: => | |
| unless $('#shade').length | |
| $(""" | |
| <div id="shade"> | |
| <div id="modal-wrapper"> | |
| <div id="modal-content"></div> | |
| </div> | |
| </div> | |
| """).hide().appendTo 'body' | |
| #actually show the modal | |
| content = $('#modal-content') | |
| content.html @content | |
| content.on 'click', 'button', (e) => | |
| e.preventDefault() | |
| #defer to (hopefully) let any resizing that's going to happen happen before we reset the modal's position | |
| setTimeout @setPosition, 1 | |
| content.on 'click', '.cancel', @hide | |
| content.on 'click', @setPosition | |
| @afterShow?() | |
| $(window).on 'resize', @setPosition | |
| @setPosition() | |
| $('#shade').fadeIn 120 | |
| setPosition: => | |
| shade = $('#shade') | |
| modal = $('#modal-content') | |
| wrapper = $('#modal-wrapper') | |
| #position shade and modal differently if the modal is too big for the window | |
| if modal.outerHeight() > $(window).height() | |
| shade.css | |
| height: $(document).height() | |
| position: 'absolute' | |
| display: 'block' | |
| wrapper.css | |
| display: 'block' | |
| verticalAlign: 'auto' | |
| margin: '100px auto' | |
| else | |
| shade.css | |
| display: 'table' | |
| position: 'fixed' | |
| height: '100%' | |
| wrapper.css | |
| display: 'table-cell' | |
| verticalAlign: 'middle' | |
| margin: '0 auto' | |
| window.Modal = Modal |
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
| div#shade { | |
| position: fixed; top: 0; left: 0; z-index: 9999; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); display: table; overflow: hidden; | |
| div#modal-wrapper { | |
| display: table-cell; vertical-align: middle; width: 100%; margin: 0 auto; text-align: center; | |
| div#modal-content { position: relative; margin: 0 auto; text-align: left; } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment