When I open a modal, the background page is automatically scrolled to the top. In my css if I remove html{ overflow-y: scroll };
I fix this behavior but now the scrollbar to the right disappears and my navbar shifts to the right the same amount of space the scrollbar was taking up.
I want to be able to keep my overflow setting and have it so the background content doesn't scroll up.
example_controller.rb
def onsale
@item= Products.first
respond_to do |format|
format.js
end
end
_header.html.erb
<div class="collapse navbar-collapse" id="navbar-collapse">
<% if user_signed_in? %>
<ul class="nav navbar-nav navbar-left">
<li><%= link_to "Sale Items", onsale_path, :remote => true %></li>
</ul>
<% end %>
</div>
application.html.erb
I put this in the body
<div id="sale-modal"></div>
onsale.js.erb
$("#onsale-modal").html('<%= escape_javascript(render 'onsale') %>');
_onsale.html.erb
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<%= image_tag @item.picture.large.url %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>$('#myModal').modal('show')</script>
application.js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap-sprockets
//= require bootstrap-select.min
//= require turbolinks
//= require fancybox
//= require_tree .
$(document).ready(function() {
$('.selectpicker').selectpicker();
$('.fancybox').fancybox({
openEffect: 'elastic',
closeEffect: 'elastic',
prevEffect: 'fade',
nextEffect: 'fade',
padding: 10
});
if ($('#infinite-scrolling').length) {
$(window).scroll(function() {
var url = $('.pagination .next_page').attr('href');
if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 60) {
// TODO - Removing this line was causing duplicates to load so it's worth investigating the cause
$('.pagination').html('Please Wait...');
return $.getScript(url);
}
});
return $(window).scroll();
}
$('#myModal').modal('show')
//Hide Scroll when modal about to show
$('#myModal').on('show.bs.modal', function () {
$('html').css({
'overflow': 'hidden'
});
});
//add Scroll back when modal is hidden
$('#myModal').on('hidden.bs.modal', function () {
$('html').css({
'overflow-y': 'scroll'
});
});
});
If I remove the script <script>$('#myModal').modal('show')</script>
from the partial and put it in application.js, like it is above, the modal doesn't show up at all. If I add the line $('#myModal').modal('show')
to onsale.js.erb, the modal will show up fine.