Skip to content

Instantly share code, notes, and snippets.

@coreyward
Last active September 7, 2018 17:14
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coreyward/1456815 to your computer and use it in GitHub Desktop.
Save coreyward/1456815 to your computer and use it in GitHub Desktop.
<div id="modal">
<div class="content"></div>
</div>
// This partial should be @imported into your layout Sass file, or included via the Asset Pipeline
//
#modal {
width: 100%;
padding: 0 20px;
position: absolute;
left: 0;
right: 0;
opacity: 0;
display: none;
@include transition(opacity 0.3s);
&:before {
display: block;
content: '';
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 50;
}
.content {
background: #fff;
box-shadow: 0 2px 25px rgba(#111, 0.3);
padding: 30px;
margin: 0 auto;
max-width: 600px;
position: relative;
z-index: 51;
border-radius: 3px;
}
}
//= jquery
//= jquery_ujs
//= modals
# in your app controller, you'll want to set the layout to nil for XHR (ajax) requests
class ApplicationController < ActionController::Base
layout -> do
request.xhr? ? false : 'application'
end
end
<%= link_to 'New Post', new_post_path, remote: true %>
# This file should be "required" into your `application.js` via the Asset Pipeline.
#
$ ->
$modal = $('#modal')
$content = $modal.find('.content')
$window = $(window)
$(document).on 'click', (e) ->
if $(e.target).is $modal
$modal.hide()
$(document).on 'ajax:success', 'a[data-remote]', (xhr, data, status) ->
$content.html(data)
$modal.css opacity: 0, display: 'block'
docW = $window.width()
docH = $window.height()
mW = $modal.outerWidth()
mH = $modal.outerHeight()
x = (docW - mW) / 2
y = ((docH - mH) / 2) + $window.scrollTop()
$modal.css left: x, top: y, opacity: 1
@crondaemon
Copy link

Hi, and thanks for the tutorial, it helped me a lot!

I'm having a problem on the very last step of the ajax stuff. In this line

https://gist.github.com/coreyward/1456815#file-modals-js-coffee-L13

data and status are undefined. Do I need to do something special in my method? I have

def new
  @model = Model.new
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment