0

I'm using an iframe inside of bootstrap modal:

<div class="modal fade" id="newsModal" tabindex="-1" role="dialog" aria-labelledby="newsModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <div>
          <div id="loadingMessage">Loading...</div> 
          <iframe width="100%" class="frame embed-responsive-item" height="350" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

That iframe is open when an element of some elements with the same class clicked:

<?php foreach($new as $news){ ?>
    <div class="post_frame" data-link="<?php echo $news['link']; ?>" data-toggle="modal" data-target="#newsModal">
         Lorem ipsum dolor sit amet
    </div>
<?php } ?>

I'm using that code to set the source of the iframe:

$('.post_frame').each(function() {
    $(this).click(function() {
        var data = $(this).data('link'),
            frame = $('.frame');

        frame.attr('src',  data);
    });     

});

To hide the preloader I use:

frame.load(function() {
    $('#loadingMessage').css('display', 'none');
});

But the preloader still there.

And when I close that modal and click on another element with the same class post_frame, The previous source content still there until the content of the new source loads.

How to create a preloader before each source is loaded?

  • 1
    `onload` in place of` `load``? https://stackoverflow.com/questions/3142837/capture-iframe-load-complete-event – ficuscr Jul 09 '18 at 19:47
  • `frame.on('load', function() {}` is working fine, But when I click another element, The preloader doesn't show up –  Jul 09 '18 at 19:58
  • I added `jQuery('#loadingMessage').css('display', 'block');`, before the onload and it worked –  Jul 09 '18 at 20:00

1 Answers1

0

Change this:

var data = $(this).data('link'),

To this:

var data = $(this).data('link');

And then remove this from where it currently is (inside function):

frame = $('.frame');

And place it in the global scope outside the function:

var frame = $('.frame');

Simon K
  • 1,503
  • 1
  • 8
  • 10