Problems showing modals when page is loaded with turbolinks

24 views
Skip to first unread message

Alexander Trust

unread,
Dec 3, 2015, 8:57:31 AM12/3/15
to Ruby on Rails: Talk
Hello.

I'm trying to use modals for the output of :notices or :errors.

In the application.html.erb I use:

<% flash.each do |name, msg| %>
       
<% if msg.is_a?(String) %>
           
<div id="modal1" class="modal">
             
<div class="modal-content">
               
<p><%= msg %></p>
             
</div>
             
<div class="modal-footer">
               
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Close</a>
             
</div>
           
</div>
         
<% end %>
<% end %>



In my application.js file I use:

var ready;
ready
= function() {


   
var modal1 = document.getElementById('#modal1');
   
if (modal1.length > 0) {
        $
('#modal1').openModal();
   
}
};


$
(document).ready(ready);
$
(document).on('page:load', ready);

I tried checking if the string is not null too, but this won't change a thing. Only if I use:

var ready;
ready
= function() {

$
('#modal1').openModal();

}

$
(document).ready(ready);
$
(document).on('page:load', ready);

it works, but then it is shown everytime a page is reloaded an I don't want this behaviour. Why do those checks not work? Any help would be appreciated.

Kind regards.

Amr Noman

unread,
Dec 12, 2015, 8:58:46 AM12/12/15
to Ruby on Rails: Talk
document.getElementByID() returns an Element object, these objects don't have a length method.
Since you're using jquery, why don't you use it there also?

if ($("#modal1").length > 0) {
 
// your code
}


Reply all
Reply to author
Forward
0 new messages