Conceal/Inactivate element when scrolling, and once scrolling comes to a halt, reveal it once more

I have been working on creating a div tag to overlay an embed tag and added some javascript to prevent users from right-clicking to download the pdf inside the embed tag (even though it may seem unnecessary, it was requested by my customer). Here is the main issue: I want users to still be able to scroll through the pdf. I set up the scrolling functionality so that every time a user scrolls, the div tag mentioned above disappears, allowing users to scroll through the pdf. However, when they stop scrolling, the div tag reappears to prevent users from right-clicking on the pdf. This is what I have implemented so far:

var wheeling;
window.addEventListener('wheel', function (e) {
        if (!wheeling) {
            console.log('start wheeling!');
            document.querySelector("#lesson_pdf").style.display = "none";
        }

        clearTimeout(wheeling);
        wheeling = setTimeout(function() {
            console.log('stop wheeling!');
            document.querySelector("#lesson_pdf").style.display = "block";
            wheeling = undefined;
        }, 300);
    });

Here is my HTML structure:

<div>
    <div style="position: relative;">
        //the embed tag I want to cover
        <embed src=" {{ getImageFile($pdf_src) }}" class="tw-w-full tw-h-[500px] pdf-reader-frame" style="position: absolute;">
    </div>
    //The div tag mentioned earlier
    <div style="position: absolute;
                height: 100%;
                width: 100%;
                display: block;
                z-index: 1;" id="lesson_pdf">
    </div>
</div>

The problem is, the current setup is not functioning as intended. Sometimes I have to scroll multiple times before being able to scroll through the pdf file. Can anyone assist me in resolving this issue?

Answer №1

Instead of creating a div overlay to prevent users from right-clicking on a PDF, why not just disable the context menu? This can be achieved using the contextmenu event, which is more efficient than toggling the visibility of an overlay (unless specifically requested by the client).

const img = document.querySelector("img")

img.addEventListener("contextmenu", (e) => {
  e.preventDefault();
  return false
})
<img src="http://via.placeholder.com/640x360" />

Answer №2

If you're looking for some helpful code, look no further! Just be sure to include the necessary CSS.

var preventElement = document.getElementById('embed-document');
preventElement.addEventListener("contextmenu", (e) => {
e.preventDefault();
});
embed {
            background:#cccccc;
            pointer-events: none;
        }
<div>
    <div id="embed-document">
      <embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" class="tw-w-full tw-h-[500px] pdf-reader-frame">
    </div>
</div>

Answer №3

If you only have a small number of PDFs to display, this method could work well.

Scroll PDF embedded in HTML

One option is to place the iframe within a div with overflow: auto, setting the height of the iframe to be very large so the PDF displays at full size. Keep the surrounding div shorter than the iframe and scroll it when needed.

The drawback is that you'll need to manually adjust the height of the embed element to match the full height of the PDF with all pages visible.

Running the code snippet on Stackoverflow using Chrome may not work due to some sandbox plugin errors. However, it worked for me outside of a sandbox (using VS Code and live server) and also on Firefox developer version. I tested it with an embed tag and it functioned properly.

.wrapper {
  position: relative;
  overflow: auto;
  
  /* Set your desired height for the PDF viewer */
  height: 500px;
}

.embed-cover {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1000;
  
  /* Should match embed height */
  height: 1000px;

  /* Just for visual demonstration, remove in practice */
  background: red;
  opacity: 0.25;
}

embed {
  width: 100%;
  
  /* Should match embed-cover height */
  height: 1000px;
}
<div class="wrapper" onContextMenu="return false;" >
  <div id="embed-cover" class="embed-cover">asd</div>
  <embed src="https://www.orimi.com/pdf-test.pdf" />
</div>

Answer №4

Not looking to dampen anyone's spirits with my response, but it's important to consider that while some solutions may help protect those who are vulnerable, like the disabled, they may not be fully accessible for everyone (not DDA/508 compatible). It's crucial to remember that determined individuals will find ways to access content regardless of barriers in place, so blocking access altogether is ineffective and can even be seen as counterproductive.

The key aspect of PDF handling lies in its ability to be openly used as a public domain standard, outlined in the fine print when using these types of files.

An interactive PDF processor engages with users during file processing, allowing for both reading and writing capabilities within the PDF format.

In essence, full accessibility should be a priority for any compliant PDF editing or reading software.

https://i.stack.imgur.com/EErXP.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with rowspan and colspan issues in Internet Explorer

Currently, I am facing the challenge of creating a table with a complex system of colspans and rowspans. If you want to take a look at it, you can view it here This is the HTML code for the table: <table cellspacing="0" cellpadding="0" style="table-la ...

How can I choose records from collection 'x' in mongodb?

I need to fetch all fields from my database using an API call Here is my code: exports.objfields = async (req, res, next) => { try { var db = mongo.connection; var objeto = req.headers.objeto; const result = db.db.collection(objeto).find( ...

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

What steps should I follow to create a cohesive background design using CSS?

Is there a way to combine two separate div elements in CSS? Currently, the image Row and col are not connected to the above SVG blob. How can I utilize the blob as a background? Based on the code provided below, they appear separated and I'm unsure ho ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

"Unraveling the Mystery: In Javascript Vue, what is the secret behind the origin of the variable 'e' found in the function

Where does the mysterious variable e in onFileChange(e) come from? In the code snippet below, we see a variable e being used in onFileChange(e). However, this variable is not declared or imported anywhere in the code. How is it possible for this to be val ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

5 Creative Techniques for Manipulating Boolean Variables in If Statements

I am receiving a unique custom header value and the values I am getting are accurate. The expected values include: true, false, undefined. However, the response associated with the value: false is incorrect. Code Snippet let deviceStatus = req.headers[ ...

The content on the page is not visible when viewing on an Android device in

After spending a considerable amount of time browsing StackOverFlow for coding solutions, I have come across a problem that I can't seem to find an answer for. Yesterday, I made some changes to the media queries on my site in order to incorporate a dr ...

Having trouble with rendering prop values in Vue.js?

Struggling to develop an ajax form component in vuejs within a Laravel 5.3 application. It seems I am facing some challenges with displaying the form fields. Can someone lend me a hand? Here is the front end code for rendering the form: <ajax-form ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

"Incorporate multiple data entries into a table with the help of Jquery

How can I store multiple values in a table row using jQuery or JavaScript when the values come from a database via Ajax? <html> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th ...

Tips for delaying the execution of numerous ajax success callbacks?

In my JavaScript code, I am facing the following situation: call_A(success_A) call_B(success_B) function call_A(success){ // make ajax request success(result) } function call_B(success){ //make ajax request success(result) } function success_A(){ ...

Newbie Query: How can I apply various font weights to a single font within the same stylesheet?

Twice I have inserted the font Acumin Pro Condensed, once with a weight of 400 and again with a weight of 700. I attempted to use both weights separately; assigning the 400 weight to an h3 tag and the 700 weight to an h2 tag. However, only the 700 font we ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...

RegEx - Finding exact matches without any additional characters trailing

I am currently trying to find matches in the given strings: 'Los Angeles, CA' 'New York, NY' 'Williamsburg, Brooklyn, NY' by comparing them with the following input strings: 'Los Angeles, CA 90001, USA' 'New ...

Is it possible to access prop properties within the ready() function?

I am seeing the error message undefined in the console, specifically originating from the ready() function. The issue I am encountering is related to attempting to assign the value of this.users.name to this.userForm.name. Can someone please point out wh ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...