Alex Fedoseev
Alex Fedoseev

Reputation: 1215

fotorama: can't get the API object (undefined)

I'm using Fotorama 4.5.0 (Rails gem) and I have a problem with getting the API object.

On page load Fotorama is in hidden div. It opens in modal on click.
Here is the code (coffee):

$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')

$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
  // resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined

$objects.on 'click', ->
  // finding index of an image
  modal.open({content: $('#fotorama-container')})
  fotorama.show(index) // index is ok

With this code fotorama object is always undefined.
Ok, I added if with check:

$objects = $('*[rel="fotorama"]')
$fotorama_div = $('.fotorama')

$fotorama_div
.on('fotorama:showend', (e, fotorama, extra) ->
  // resizing fotorama
).fotorama()
fotorama = $fotorama_div.data('fotorama')
console.log(fotorama) // here is undefined

$objects.on 'click', ->
  // finding index of an image
  modal.open({content: $('#fotorama-container')})
  if typeof fotorama == "undefined"
    fotorama = $fotorama_div.data('fotorama')
    console.log(fotorama) // here is undefined after the first click on object
  fotorama.show(index) // index is ok

After the first click on object — fotorama is still undefined, but after I'm closing a modal and doing the second click — I get fotorama object and everything works as expected.

And when I doing $fotorama_div.data('fotorama') in console, it works.

How can I get fotorama object on page load?

Upvotes: 1

Views: 2310

Answers (2)

Tiny Brain
Tiny Brain

Reputation: 640

I had the same problem and found the reason why it returns undefined.
If the $fotorama_div has style="display: none;" attribute then $fotorama_div.data('fotorama') will return undefined.

So the solution is to remove this attribute style="display: none;" before you run $fotorama_div.data('fotorama').

$fotorama_div.show().data('fotorama');

If it still returns undefined then check if any parents of $fotorama_div has display: none css.

let hiddenParents = $fotorama_div.parents().filter(function() { 
    return $(this).css('display') == 'none';
});
hiddenParents.show();
let fotorama = $fotorama_div.data('fotorama');
hiddenParents.hide();
// Now enjoy with your fotorama from here.

Upvotes: 0

d23
d23

Reputation: 186

I was having the exact same problem - loading fotorama in a div gave "undefined" in console, only after showing the div again the fotorama object was loaded correctly.

I found the cause of this was loading fotorama in an object with "display: none;" css styling. I dont know why but if fotorama loads in something that is hidden then it breaks.

I dont know any RoR but my sugestion would be to first show the modal, then load fotorama $fotorama_div.fotorama() after the modal is opened.

Upvotes: 1

Related Questions