Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting scroll event of Iframe called by AJAX reqest

i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.

Main.php

 <html>
 <!--ajax request-->
 <script type="text/javascript">
  $(document).on('click','#nextpdf',function(event) {

  event.preventDefault();

  var reg = $(this).attr("href");
  var str = reg.split('?')[1];

  $.ajax({

    type: "GET",
    url: '../functions/pdfreader.php',
    data: 'pdfxs='+str+'',
    cache:false,
      async: false,
     success: function(data) {
   // data is ur summary
  $('.refresh').html(data);
  return false;
        }

   });//end of ajax

      });


</script>
  <?php

     while($obj = $c_content->fetch())
 {
   $title = $obj['lecture_title'];

    echo '<article class="comment2">

    //pdf link
   <div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
  <p><a href="../functions/pdfreader.php?'.$title.'"" 
  style="color:#999" id="nextpdf">'.$title.'</a></p>
   </div>
</div>
 </article>
   ';

    }

    ?>
    </html>

pdfreader.php

//detect iframe pdf scroll
               <script type="text/javascript">
     $("myiframe").load(function () {
     var iframe = $("myiframe").contents();

     $(iframe).scroll(function () { 
      alert('scrolling...');
        });
           });
        </script>

  <?php



         ........
        while($obj = $gettrend->fetch())
    {
       $coursefile = $obj['lecture_content'];
          //this is my iframe
       echo '<div class="mov_pdf_frame"><iframe id="myiframe"
      src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'" 
      id="pdf_content"
     width="700px" height="800px" type="application/pdf">
       </iframe></div>';
             }
                 ?>

The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?

i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/

like image 427
Alexander Omoruyi Avatar asked Feb 20 '18 15:02

Alexander Omoruyi


3 Answers

First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").

Here's a working fiddle (for iframe scroll detection)


UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).

Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:

Event type: Event names

App: Init

Batch: Exec

Bookmark: Mouse Up

Console: Exec

Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave

External: Exec

Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate

Link: Mouse Up

Menu: Exec

Page: Open, Close

Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit


So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.

Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D

like image 59
Bernardo Dal Corno Avatar answered Oct 19 '22 13:10

Bernardo Dal Corno


Because this question is asked a long time ago, i think i need to help with my experience before.

The answer is: You can not

Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.

if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).

But, hei.. how if our client using another apps? we will confused more


The way to do this is only build your own pdf viewer.

we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/

but here i only will show you to use pdf.js which created by mozilla.

main.php

<style>
.preview{
    display:none;
    width: 400px;
    height: 400px;
    border: 1px solid black;
}

</style>
<a href="pdfreader.php?pdfxs=test.pdf" style="color:#999;" id="nextpdf">file/test.pdf</a><br>
<a href="pdfreader.php?pdfxs=test1.pdf" style="color:#999;" id="nextpdf">file/test1.pdf</a><br>
<div class="preview">
    <iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $(document).on('click', '#nextpdf', function(e){
        e.preventDefault();
        $('#myiframe').attr('src', $(this).attr('href'));
        $('.preview').show();
    });

    //handle iframe on scroll
    $('#myiframe').on('load', function () {
        $(this).contents().scroll(function () { 
            console.log('scrolled');
        }).click(function(){
            console.log('clicked');
        });
    });

});


</script>

pdfreader.php

<?php 
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) ||  !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
    <div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

<script>
$(function(){

    //original script : https://gist.github.com/fcingolani/3300351
    function renderPDF(url, canvasContainer, options) {
        var options = options || { scale: 1 };

        function renderPage(page) {
            var viewport = page.getViewport(options.scale);
            var canvas = $(document.createElement('canvas'));
            var renderContext = {
              canvasContext: canvas[0].getContext('2d'),
              viewport: viewport
            };
            canvas.attr('width', viewport.width).attr('height', viewport.height);

            canvasContainer.append(canvas);
            page.render(renderContext);
        }

        function renderPages(pdfDoc) {
            for(var num = 1; num <= pdfDoc.numPages; num++)
                pdfDoc.getPage(num).then(renderPage);
        }
        PDFJS.disableWorker = true;
        PDFJS.getDocument(url).then(renderPages);
    }

    renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>

Note: i put pdf on folder file/

in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.

and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js

like image 45
plonknimbuzz Avatar answered Oct 19 '22 14:10

plonknimbuzz


Please try this

iframe.on( "scroll", handler ) 
like image 1
Priya Avatar answered Oct 19 '22 12:10

Priya