javascriptjqueryruby-on-railsrubyjquery-masonry

Masonry not working with Modal


The inspirations are loaded as a single column instead of horizontally across the screen. It works if I take it out of the modal, but why not inside?

Inside Modal

enter image description here

Outside Modal

enter image description here

_form

<div id="inspirations-margin" class="transitions-enabled">
  <% @inspirations.each do |inspiration| %>
    <div class="box panel panel-default">
      <%= inspiration.name %>
    </div>
  <% end %>
</div>

modals.js.coffee

$ ->
  modal_holder_selector = '#modal-holder'
  modal_selector = '.modal'

  $(document).on 'click', 'a[data-modal]', ->
    location = $(this).attr('href')
    #Load modal dialog from server
    $.get location, (data)->
      $(modal_holder_selector).html(data).
      find(modal_selector).modal()
    false

  $(document).on 'ajax:success',
    'form[data-modal]', (event, data, status, xhr)->
      url = xhr.getResponseHeader('Location')
      if url
        # Redirect to url
        window.location = url
      else
        # Remove old modal backdrop
        $('.modal-backdrop').remove()

        # Replace old modal with new one
        $(modal_holder_selector).html(data).
        find(modal_selector).modal()

      false

inspirations.js.coffee

$ ->
  $('#inspirations-margin').imagesLoaded ->
    $('#inspirations-margin').masonry
      itemSelector: '.box'
      isFitWidth: true

I see this guy ran into a similar problem, but never got help.


Solution

  • The problem is that you're initializing masonry before the modal is displayed. You have to call it after you show the modal.

    $(modal_holder_selector).html(data).
    find(modal_selector).modal()
    $('#inspirations-margin').imagesLoaded ->
        $('#inspirations-margin').masonry
          itemSelector: '.box'
          isFitWidth: true
    

    That code should go in your callbacks where you show the modal