I have a section of ERB code in my view that fetches an array of image objects and creates a grid of thumbnails. I want to use jQuery's fadeIn and fadeOut functionality to cycle the thumbnails on and off. I've looked at other examples of how to set this up, but my code is still not working.
The number of images in the array is dynamic, so I have to set my tag id's dynamically. That part of the code seems to be working. All images are set to
I then have a jQuery script which should cycle through the images by fading them in and out. So far as I can tell, the script looks right. Yet for some reason it doesn't execute when the page renders. None of my variables nor the function are defined in the console. There are no errors either.
<div class="media-container top gallery-container" style="margin:-12px;height:200px;">
<% c.photos.each_with_index do |m,i| %>
<a href="<%= m.image.url %>">
<div class="gallery-photo" id="photo_<%= "#{c.id}_#{i}" %>" style="z-index:<%= 10+i %>;position:absolute;width:100%;height:100%;background-image: url('<%= m.image.url(:medium) %>');">
</div>
</a>
<% end %>
<br style="clear:both" />
<% length = c.photos.length %>
<% galleryID = c.id %>
<%= javascript_tag do %>
$(document).ready(function(){
var length = '<%= length.to_json.html_safe %>';
var galleryID = '<%= galleryID.to_json.html_safe %>';
var runSlide = function(g, p) {
$('#photo_' + g + '_' + p)
.fadeOut(1500)
.delay(3500)
.fadeIn(1500);
};
for (var i = 0; i < length; i++) {
runSlide(galleryID, i);
}
});
<% end %>
</div>
My problem is that I can't figure out why the script isn't running. Ideally the script would not be placed where it is, however it depends on the value of length
and galleryID
, which are only available within the context of the Ruby loop.